From a819dd568d89bfbbf0b8b68da016cb5c1a0bc035 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Mon, 17 Jun 2024 14:24:20 +0200 Subject: [PATCH] utils: Return the old value in the set method of ChannelObservable --- crates/matrix-sdk/src/utils.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/matrix-sdk/src/utils.rs b/crates/matrix-sdk/src/utils.rs index 5c02e7b6751..bef0b63b042 100644 --- a/crates/matrix-sdk/src/utils.rs +++ b/crates/matrix-sdk/src/utils.rs @@ -76,10 +76,16 @@ impl ChannelObservable { } /// 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. @@ -183,3 +189,17 @@ impl IntoRawStateEventContent for &Box { 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); + } +}