// TODO: This implementation is actually broken in that it will only use gpui::{Entity, ModelContext, View, ViewContext}; use smol::{channel, lock::RwLock}; use std::ops::Deref; use std::sync::Arc; pub struct Sender { value: Arc>, updated: channel::Sender<()>, } #[derive(Clone)] pub struct Receiver { value: Arc>, updated: channel::Receiver<()>, } impl Sender { pub async fn update(&mut self, f: impl FnOnce(&mut T) -> R) -> R { let result = f(&mut *self.value.write().await); self.updated.send(()).await.unwrap(); result } } impl Receiver { pub async fn updated(&self) { let _ = self.updated.recv().await; } pub async fn read<'a>(&'a self) -> impl 'a + Deref { self.value.read().await } } // TODO: These implementations are broken because they only handle a single update. impl Receiver { pub fn notify_model_on_change(&self, ctx: &mut ModelContext) { let watch = self.clone(); let _ = ctx.spawn_local(async move { watch.updated().await }, |_, _, ctx| { ctx.notify() }); } pub fn notify_view_on_change(&self, ctx: &mut ViewContext) { let watch = self.clone(); let _ = ctx.spawn_local(async move { watch.updated().await }, |_, _, ctx| { ctx.notify() }); } } pub fn channel(value: T) -> (Sender, Receiver) { let value = Arc::new(RwLock::new(value)); let (s, r) = channel::unbounded(); let sender = Sender { value: value.clone(), updated: s, }; let receiver = Receiver { value, updated: r }; (sender, receiver) }