-
Notifications
You must be signed in to change notification settings - Fork 49
Ownership of RootRender
#93
Comments
Hi! I was experimenting with the idea to trigger async calls too. struct Data {
value: i32,
}
enum Msg {
Add,
Minus,
}
struct Entity {
tx: mpsc::UnboundedSender<Msg>,
data: Rc<Mutex<Data>>,
}
fn main() {
let (tx, rx) = mpsc::unbounded::<Msg>();
let data = Rc::new(Mutex::new(Data { value: 0 }));
let entity = Entity { data, tx };
let vdom = Vdom::new(&body, entity));
let data_handle = data.clone();
let rendering = async move {
while let Some(msg) = rx.next().await {
let data = data_clone.lock().await;
match msg {
Msg::Add => {
data.value +=1;
}
Msg::Minus => {
data.value -=1;
}
}
vdom.weak().render().compat().await.unwrap();
}
};
spawn_local(rendering)
}
Since tx is cloneable, you can then move the sender on your event handler and eventually on your async task. impl Render for Entity {
fn render<'a>(&self, ctx: &mut RenderContext<'a>) -> Node<'a> {
let tx = self.tx.clone();
let closure = move |_, _, event| {
let tx = tx.clone();
let fut = async move {
tx.send(Msg::Add).await.unwrap();
};
spawn_local(fut);
};
// mount the closure on your view.
}
} Therefore you can send msg that trigger mutation sometimes later. Previously if we want to do mutation in the closure, we would have to use RootRender which would only points to the one mounted to the vdom. By decoupling data mutation and RootRender, if nested components is presents, we can always mutate on self instead of traversing from RootRender to the current component. I've create a helper-crate to record stuff on my journey of learning to use dodrio(and typed-html), you can find a more detailed version in that repo. I'm not sure if this is optimal though. Just finding it ergonomic to play with dodrio. |
When you want to respond to a user event, you use the following builder method
The problem comes if you want to then pass the
&mut dyn RootRender
to a future, for example if you want to update state based on some asynchronous event like an api call. Because futures must be 'static, there's no way to do it.A potential solution would be for that field to give you something like
Rc<Box<dyn RootRender>>
, thereby giving you ownership, so you can use it at any point in the future.What do you think about this?
EDIT I guess it would need to be
Rc<RefCell<dyn RootRender>>
so you could mutate the state.The text was updated successfully, but these errors were encountered: