use std::rc::Rc;
use super::observer::{self, EffectId};
pub struct Watcher {
id: EffectId,
stopped: bool,
}
impl Watcher {
pub fn id(&self) -> EffectId {
self.id
}
pub fn stop(&mut self) {
if !self.stopped {
self.stopped = true;
observer::remove_effect(self.id);
}
}
}
impl Drop for Watcher {
fn drop(&mut self) {
self.stop();
}
}
pub fn watch(f: impl Fn() + 'static) -> Watcher {
let callback: Rc<dyn Fn()> = Rc::new(f);
let id = observer::register_watcher(Rc::clone(&callback));
observer::with_effect(id, move || callback());
Watcher { id, stopped: false }
}