#Need help writing an async feature
2 messages · Page 1 of 1 (latest)
use reactivate::Reactive;
#[tokio::main]
async fn main() {
let r = Reactive::new(10);
let d = r.derive(|val| val + 5);
let fut = r.update_async(move |_| async move {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
20
});
println!("{:?}", r); // Reactive(10)
println!("{:?}", d); // Reactive(15)
fut.await;
println!("{:?}", r); // Reactive(20)
println!("{:?}", d); // Reactive(25)
}
i have tried using tokio oneshot channel but i just can't get it to work
pub fn update_async<F, Fut>(&self, f: F) -> tokio::sync::oneshot::Receiver<()>
where
F: FnOnce(&T) -> Fut + Send + 'static,
Fut: std::future::Future<Output = T> + Send + 'static,
T: PartialEq + Send + 'static,
{
let (tx, rx) = tokio::sync::oneshot::channel();
let fut = async move {
let new_val = f(&self.value.lock().unwrap()).await;
let mut guard = self.acq_val_lock();
*guard = new_val;
for obs in self.acq_obs_lock().iter_mut() {
obs(&*guard);
}
let _ = tx.send(());
};
tokio::spawn(fut);
rx
}