From 9f3abe920271996cc4a9c533ad5e0e75e3d18a3d Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sun, 24 Nov 2019 11:25:14 +0100 Subject: Spawn `Command` futures in `iced_web` --- web/src/lib.rs | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) (limited to 'web/src/lib.rs') diff --git a/web/src/lib.rs b/web/src/lib.rs index ac7f570c..dd401c31 100644 --- a/web/src/lib.rs +++ b/web/src/lib.rs @@ -57,7 +57,7 @@ #![deny(unsafe_code)] #![deny(rust_2018_idioms)] use dodrio::bumpalo; -use std::cell::RefCell; +use std::{cell::RefCell, rc::Rc}; mod bus; mod element; @@ -87,7 +87,7 @@ pub trait Application { /// The type of __messages__ your [`Application`] will produce. /// /// [`Application`]: trait.Application.html - type Message; + type Message: Clone; /// Initializes the [`Application`]. /// @@ -137,10 +137,10 @@ pub trait Application { where Self: 'static + Sized, { - // TODO: Spawn command - let (app, _command) = Self::new(); + let (app, command) = Self::new(); + let mut instance = Instance::new(app); - let instance = Instance::new(app); + instance.spawn(command); let window = web_sys::window().unwrap(); let document = window.document().unwrap(); @@ -151,26 +151,42 @@ pub trait Application { } } +#[derive(Clone)] struct Instance { - ui: RefCell>>, + ui: Rc>>>, } -impl Instance { +impl Instance +where + Message: 'static + Clone, +{ fn new(ui: impl Application + 'static) -> Self { Self { - ui: RefCell::new(Box::new(ui)), + ui: Rc::new(RefCell::new(Box::new(ui))), } } fn update(&mut self, message: Message) { - // TODO: Spawn command - let _command = self.ui.borrow_mut().update(message); + let command = self.ui.borrow_mut().update(message); + + self.spawn(command); + } + + fn spawn(&mut self, command: Command) { + use futures::FutureExt; + + for future in command.futures() { + let mut instance = self.clone(); + let future = future.map(move |message| instance.update(message)); + + wasm_bindgen_futures::spawn_local(future); + } } } impl dodrio::Render for Instance where - Message: 'static, + Message: 'static + Clone, { fn render<'a, 'bump>( &'a self, -- cgit