fix: ffi Subscription (#505)

This commit is contained in:
Leon Zhao 2024-10-10 15:14:39 +08:00 committed by GitHub
parent f2365a837b
commit 5914d32b38
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -419,7 +419,7 @@ impl LoroDoc {
callback.on_local_update(update.to_vec()); callback.on_local_update(update.to_vec());
true true
})); }));
Arc::new(Subscription(Arc::new(Mutex::new(s)))) Arc::new(Subscription(Mutex::new(Some(s))))
} }
/// Estimate the size of the document states in memory. /// Estimate the size of the document states in memory.
@ -684,30 +684,26 @@ pub trait Unsubscriber: Sync + Send {
/// A handle to a subscription created by GPUI. When dropped, the subscription /// A handle to a subscription created by GPUI. When dropped, the subscription
/// is cancelled and the callback will no longer be invoked. /// is cancelled and the callback will no longer be invoked.
pub struct Subscription(Arc<Mutex<loro::Subscription>>); pub struct Subscription(Mutex<Option<loro::Subscription>>);
impl Subscription { impl Subscription {
pub fn new(unsubscribe: Arc<dyn Unsubscriber>) -> Self { pub fn new(unsubscribe: Arc<dyn Unsubscriber>) -> Self {
Self(Arc::new(Mutex::new(loro::Subscription::new(move || { Self(Mutex::new(Some(loro::Subscription::new(move || {
unsubscribe.on_unsubscribe() unsubscribe.on_unsubscribe()
})))) }))))
} }
pub fn detach(self: Arc<Self>) { pub fn detach(self: Arc<Self>) {
let s = Arc::try_unwrap(self) let s = self.0.try_lock().unwrap().take().unwrap();
.map_err(|_| "Arc::try_unwrap Subscription failed") // let s = Arc::try_unwrap(self)
.unwrap() // .map_err(|_| "Arc::try_unwrap Subscription failed")
.0; // .unwrap()
let s = Arc::try_unwrap(s) // .0;
.map_err(|_| "Arc::try_unwrap Subscription failed")
.unwrap(); s.detach();
s.into_inner().unwrap().detach();
} }
} }
unsafe impl Send for Subscription {}
unsafe impl Sync for Subscription {}
impl std::fmt::Debug for Subscription { impl std::fmt::Debug for Subscription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Subscription") f.write_str("Subscription")
@ -716,7 +712,7 @@ impl std::fmt::Debug for Subscription {
impl From<loro::Subscription> for Subscription { impl From<loro::Subscription> for Subscription {
fn from(value: loro::Subscription) -> Self { fn from(value: loro::Subscription) -> Self {
Self(Arc::new(Mutex::new(value))) Self(Mutex::new(Some(value)))
} }
} }