use crate::runtime::RuntimeInner;
use std::cell::RefCell;
use std::rc::{Rc, Weak};
pub struct Effect {
id: usize,
runtime: Weak<RefCell<RuntimeInner>>,
}
impl Effect {
pub(crate) fn new_in_scope<F>(effect: F, id: usize, runtime: Rc<RefCell<RuntimeInner>>) -> Self
where
F: Fn() + 'static,
{
Self::new_in_scope_with_lifecycle(effect, id, runtime, true)
}
pub(crate) fn new_in_scope_with_lifecycle<F>(
effect: F,
id: usize,
runtime: Rc<RefCell<RuntimeInner>>,
run_immediately: bool,
) -> Self
where
F: Fn() + 'static,
{
let effect = Rc::new(effect);
let effect_clone = Rc::clone(&effect);
runtime.borrow().create_observer(id, move || {
effect_clone();
});
if run_immediately {
RuntimeInner::with_observer_scoped(&runtime, id, || {
effect();
});
}
Self {
id,
runtime: Rc::downgrade(&runtime),
}
}
}
impl Drop for Effect {
fn drop(&mut self) {
if let Some(runtime) = self.runtime.upgrade() {
runtime.borrow().remove_observer(self.id);
}
}
}