Skip to content

Commit

Permalink
utils: Return the old value in the set method of ChannelObservable
Browse files Browse the repository at this point in the history
  • Loading branch information
poljar committed Jul 1, 2024
1 parent 7fee66d commit a819dd5
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions crates/matrix-sdk/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,16 @@ impl<T: 'static + Send + Clone> ChannelObservable<T> {
}

/// Set the underlying data to the new value.
pub(crate) fn set(&self, new_value: T) {
*self.value.write().unwrap() = new_value.to_owned();
pub(crate) fn set(&self, new_value: T) -> T {
let old_value = {
let mut guard = self.value.write().unwrap();
std::mem::replace(&mut (*guard), new_value.clone())
};

// We're ignoring the error case where no receivers exist.
let _ = self.channel.send(new_value);

old_value
}

/// Get the current value of the underlying data.
Expand Down Expand Up @@ -183,3 +189,17 @@ impl IntoRawStateEventContent for &Box<RawJsonValue> {
self.clone().into_raw_state_event_content()
}
}

#[cfg(test)]
mod test {
#[cfg(feature = "e2e-encryption")]
#[test]
fn test_channel_observable_get_set() {
let observable = super::ChannelObservable::new(0);

assert_eq!(observable.get(), 0);
assert_eq!(observable.set(1), 0);
assert_eq!(observable.set(10), 1);
assert_eq!(observable.get(), 10);
}
}

0 comments on commit a819dd5

Please sign in to comment.