Skip to content

Commit

Permalink
im: Only emit VectorDiff::Clear from ObservableVector::clear when…
Browse files Browse the repository at this point in the history
… necessary

The idea behind this patch is to avoid emitting a `VectorDiff::Clear`
when an `ObservableVector` is already empty.
  • Loading branch information
Hywan authored Mar 6, 2024
1 parent 61ab457 commit 90125a2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
16 changes: 12 additions & 4 deletions eyeball-im/src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,19 @@ impl<T: Clone + Send + Sync + 'static> ObservableVector<T> {

/// Clear out all of the elements in this `Vector` and notify subscribers.
pub fn clear(&mut self) {
#[cfg(feature = "tracing")]
tracing::debug!(target: "eyeball_im::vector::update", "clear");
let already_empty = self.values.is_empty();

self.values.clear();
self.broadcast_diff(VectorDiff::Clear);
#[cfg(feature = "tracing")]
tracing::debug!(
target: "eyeball_im::vector::update",
nop = already_empty.then_some(true),
"clear"
);

if !already_empty {
self.values.clear();
self.broadcast_diff(VectorDiff::Clear);
}
}

/// Add an element at the front of the list and notify subscribers.
Expand Down
21 changes: 20 additions & 1 deletion eyeball-im/tests/it/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use imbl::{vector, Vector};
use stream_assert::{assert_next_eq, assert_pending};
use stream_assert::{assert_closed, assert_next_eq, assert_pending};

use eyeball_im::{ObservableVector, ObservableVectorEntry, VectorDiff};

Expand Down Expand Up @@ -58,6 +58,25 @@ fn truncate() {
assert!(ob.is_empty());
}

#[test]
fn clear() {
let mut ob: ObservableVector<i32> = ObservableVector::from(vector![1, 2]);
let mut sub = ob.subscribe().into_stream();
assert_pending!(sub);

ob.clear();
assert_next_eq!(sub, VectorDiff::Clear);
assert!(ob.is_empty());

// Clearing again. The vector is empty now. We don't expect a
// `VectorDiff::Clear`.
ob.clear();
assert_pending!(sub);

drop(ob);
assert_closed!(sub);
}

#[test]
fn for_each() {
let mut ob: ObservableVector<i32> = ObservableVector::from(vector![0, 10, 1, 2, 4, 33, 5]);
Expand Down

0 comments on commit 90125a2

Please sign in to comment.