From e730d97f61bc2edc77d2f061b6a763c4d0a948df Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 28 Jan 2022 18:43:20 +0700 Subject: Implement `time` module for `wasm-bindgen` backend in `iced_futures` --- futures/Cargo.toml | 1 + futures/src/backend/wasm/wasm_bindgen.rs | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) (limited to 'futures') diff --git a/futures/Cargo.toml b/futures/Cargo.toml index aa55df1e..93c7693d 100644 --- a/futures/Cargo.toml +++ b/futures/Cargo.toml @@ -36,6 +36,7 @@ optional = true [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen-futures = "0.4" +wasm-timer = "0.2" [package.metadata.docs.rs] rustdoc-args = ["--cfg", "docsrs"] diff --git a/futures/src/backend/wasm/wasm_bindgen.rs b/futures/src/backend/wasm/wasm_bindgen.rs index e914aeba..b726501a 100644 --- a/futures/src/backend/wasm/wasm_bindgen.rs +++ b/futures/src/backend/wasm/wasm_bindgen.rs @@ -13,3 +13,47 @@ impl crate::Executor for Executor { wasm_bindgen_futures::spawn_local(future); } } + +pub mod time { + //! Listen and react to time. + use crate::subscription::{self, Subscription}; + use crate::BoxStream; + + /// Returns a [`Subscription`] that produces messages at a set interval. + /// + /// The first message is produced after a `duration`, and then continues to + /// produce more messages every `duration` after that. + pub fn every( + duration: std::time::Duration, + ) -> Subscription { + Subscription::from_recipe(Every(duration)) + } + + #[derive(Debug)] + struct Every(std::time::Duration); + + impl subscription::Recipe for Every + where + H: std::hash::Hasher, + { + type Output = wasm_timer::Instant; + + fn hash(&self, state: &mut H) { + use std::hash::Hash; + + std::any::TypeId::of::().hash(state); + self.0.hash(state); + } + + fn stream( + self: Box, + _input: BoxStream, + ) -> BoxStream { + use futures::stream::StreamExt; + + wasm_timer::Interval::new(self.0) + .map(|_| wasm_timer::Instant::now()) + .boxed_local() + } + } +} -- cgit