Merge pull request #2747 from iced-rs/time-repeat-subscription

Implement `time::repeat` and simplify `Subscription::run_with`
This commit is contained in:
Héctor 2025-01-24 18:59:44 +01:00 committed by GitHub
commit 5eedf5798c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 88 additions and 61 deletions

View file

@ -2,3 +2,28 @@
pub use web_time::Duration; pub use web_time::Duration;
pub use web_time::Instant; pub use web_time::Instant;
/// Creates a [`Duration`] representing the given amount of milliseconds.
pub fn milliseconds(milliseconds: u64) -> Duration {
Duration::from_millis(milliseconds)
}
/// Creates a [`Duration`] representing the given amount of seconds.
pub fn seconds(seconds: u64) -> Duration {
Duration::from_secs(seconds)
}
/// Creates a [`Duration`] representing the given amount of minutes.
pub fn minutes(minutes: u64) -> Duration {
seconds(minutes * 60)
}
/// Creates a [`Duration`] representing the given amount of hours.
pub fn hours(hours: u64) -> Duration {
minutes(hours * 60)
}
/// Creates a [`Duration`] representing the given amount of days.
pub fn days(days: u64) -> Duration {
hours(days * 24)
}

View file

@ -4,6 +4,7 @@ use iced::mouse;
use iced::widget::canvas::{ use iced::widget::canvas::{
self, stroke, Cache, Canvas, Geometry, Path, Stroke, self, stroke, Cache, Canvas, Geometry, Path, Stroke,
}; };
use iced::window;
use iced::{Element, Fill, Point, Rectangle, Renderer, Subscription, Theme}; use iced::{Element, Fill, Point, Rectangle, Renderer, Subscription, Theme};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -34,8 +35,7 @@ impl Arc {
} }
fn subscription(&self) -> Subscription<Message> { fn subscription(&self) -> Subscription<Message> {
iced::time::every(std::time::Duration::from_millis(10)) window::frames().map(|_| Message::Tick)
.map(|_| Message::Tick)
} }
} }

View file

@ -1,5 +1,5 @@
use iced::mouse; use iced::mouse;
use iced::time; use iced::time::{self, milliseconds};
use iced::widget::canvas::{stroke, Cache, Geometry, LineCap, Path, Stroke}; use iced::widget::canvas::{stroke, Cache, Geometry, LineCap, Path, Stroke};
use iced::widget::{canvas, container}; use iced::widget::{canvas, container};
use iced::{alignment, Radians}; use iced::{alignment, Radians};
@ -49,7 +49,7 @@ impl Clock {
} }
fn subscription(&self) -> Subscription<Message> { fn subscription(&self) -> Subscription<Message> {
time::every(time::Duration::from_millis(500)) time::every(milliseconds(500))
.map(|_| Message::Tick(chrono::offset::Local::now())) .map(|_| Message::Tick(chrono::offset::Local::now()))
} }

View file

@ -5,12 +5,11 @@ mod preset;
use grid::Grid; use grid::Grid;
use preset::Preset; use preset::Preset;
use iced::time; use iced::time::{self, milliseconds};
use iced::widget::{ use iced::widget::{
button, checkbox, column, container, pick_list, row, slider, text, button, checkbox, column, container, pick_list, row, slider, text,
}; };
use iced::{Center, Element, Fill, Subscription, Task, Theme}; use iced::{Center, Element, Fill, Subscription, Task, Theme};
use std::time::Duration;
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
@ -112,7 +111,7 @@ impl GameOfLife {
fn subscription(&self) -> Subscription<Message> { fn subscription(&self) -> Subscription<Message> {
if self.is_playing { if self.is_playing {
time::every(Duration::from_millis(1000 / self.speed as u64)) time::every(milliseconds(1000 / self.speed as u64))
.map(|_| Message::Tick) .map(|_| Message::Tick)
} else { } else {
Subscription::none() Subscription::none()
@ -191,6 +190,7 @@ mod grid {
use crate::Preset; use crate::Preset;
use iced::alignment; use iced::alignment;
use iced::mouse; use iced::mouse;
use iced::time::{Duration, Instant};
use iced::touch; use iced::touch;
use iced::widget::canvas; use iced::widget::canvas;
use iced::widget::canvas::{ use iced::widget::canvas::{
@ -202,7 +202,6 @@ mod grid {
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use std::future::Future; use std::future::Future;
use std::ops::RangeInclusive; use std::ops::RangeInclusive;
use std::time::{Duration, Instant};
pub struct Grid { pub struct Grid {
state: State, state: State,

View file

@ -1,10 +1,8 @@
use iced::keyboard; use iced::keyboard;
use iced::time; use iced::time::{self, milliseconds, Duration, Instant};
use iced::widget::{button, center, column, row, text}; use iced::widget::{button, center, column, row, text};
use iced::{Center, Element, Subscription, Theme}; use iced::{Center, Element, Subscription, Theme};
use std::time::{Duration, Instant};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::application("Stopwatch - Iced", Stopwatch::update, Stopwatch::view) iced::application("Stopwatch - Iced", Stopwatch::update, Stopwatch::view)
.subscription(Stopwatch::subscription) .subscription(Stopwatch::subscription)
@ -63,7 +61,7 @@ impl Stopwatch {
let tick = match self.state { let tick = match self.state {
State::Idle => Subscription::none(), State::Idle => Subscription::none(),
State::Ticking { .. } => { State::Ticking { .. } => {
time::every(Duration::from_millis(10)).map(Message::Tick) time::every(milliseconds(10)).map(Message::Tick)
} }
}; };

View file

@ -1,5 +1,5 @@
use iced::mouse; use iced::mouse;
use iced::time::{self, Instant}; use iced::time::{self, milliseconds, Instant};
use iced::widget::canvas; use iced::widget::canvas;
use iced::{ use iced::{
Color, Element, Fill, Font, Point, Rectangle, Renderer, Subscription, Theme, Color, Element, Fill, Font, Point, Rectangle, Renderer, Subscription, Theme,
@ -40,7 +40,7 @@ impl TheMatrix {
} }
fn subscription(&self) -> Subscription<Message> { fn subscription(&self) -> Subscription<Message> {
time::every(std::time::Duration::from_millis(50)).map(Message::Tick) time::every(milliseconds(50)).map(Message::Tick)
} }
} }

View file

@ -162,7 +162,6 @@ impl Default for App {
mod toast { mod toast {
use std::fmt; use std::fmt;
use std::time::{Duration, Instant};
use iced::advanced::layout::{self, Layout}; use iced::advanced::layout::{self, Layout};
use iced::advanced::overlay; use iced::advanced::overlay;
@ -171,6 +170,7 @@ mod toast {
use iced::advanced::{Clipboard, Shell, Widget}; use iced::advanced::{Clipboard, Shell, Widget};
use iced::mouse; use iced::mouse;
use iced::theme; use iced::theme;
use iced::time::{self, Duration, Instant};
use iced::widget::{ use iced::widget::{
button, column, container, horizontal_rule, horizontal_space, row, text, button, column, container, horizontal_rule, horizontal_space, row, text,
}; };
@ -502,9 +502,8 @@ mod toast {
self.instants.iter_mut().enumerate().for_each( self.instants.iter_mut().enumerate().for_each(
|(index, maybe_instant)| { |(index, maybe_instant)| {
if let Some(instant) = maybe_instant.as_mut() { if let Some(instant) = maybe_instant.as_mut() {
let remaining = let remaining = time::seconds(self.timeout_secs)
Duration::from_secs(self.timeout_secs) .saturating_sub(instant.elapsed());
.saturating_sub(instant.elapsed());
if remaining == Duration::ZERO { if remaining == Duration::ZERO {
maybe_instant.take(); maybe_instant.take();

View file

@ -22,40 +22,25 @@ impl crate::Executor for Executor {
pub mod time { pub mod time {
//! Listen and react to time. //! Listen and react to time.
use crate::subscription::{self, Hasher, Subscription}; use crate::core::time::{Duration, Instant};
use crate::stream;
use crate::subscription::Subscription;
use crate::MaybeSend;
use futures::SinkExt;
use std::future::Future;
/// Returns a [`Subscription`] that produces messages at a set interval. /// Returns a [`Subscription`] that produces messages at a set interval.
/// ///
/// The first message is produced after a `duration`, and then continues to /// The first message is produced after a `duration`, and then continues to
/// produce more messages every `duration` after that. /// produce more messages every `duration` after that.
pub fn every( pub fn every(duration: Duration) -> Subscription<Instant> {
duration: std::time::Duration, Subscription::run_with(duration, |duration| {
) -> Subscription<std::time::Instant> {
subscription::from_recipe(Every(duration))
}
#[derive(Debug)]
struct Every(std::time::Duration);
impl subscription::Recipe for Every {
type Output = std::time::Instant;
fn hash(&self, state: &mut Hasher) {
use std::hash::Hash;
std::any::TypeId::of::<Self>().hash(state);
self.0.hash(state);
}
fn stream(
self: Box<Self>,
_input: subscription::EventStream,
) -> futures::stream::BoxStream<'static, Self::Output> {
use futures::stream::StreamExt; use futures::stream::StreamExt;
let start = tokio::time::Instant::now() + self.0; let start = tokio::time::Instant::now() + *duration;
let mut interval = tokio::time::interval_at(start, self.0); let mut interval = tokio::time::interval_at(start, *duration);
interval.set_missed_tick_behavior( interval.set_missed_tick_behavior(
tokio::time::MissedTickBehavior::Skip, tokio::time::MissedTickBehavior::Skip,
); );
@ -67,6 +52,27 @@ pub mod time {
}; };
stream.map(tokio::time::Instant::into_std).boxed() stream.map(tokio::time::Instant::into_std).boxed()
} })
}
/// Returns a [`Subscription`] that runs the given async function at a
/// set interval; producing the result of the function as output.
pub fn repeat<F, T>(f: fn() -> F, interval: Duration) -> Subscription<T>
where
F: Future<Output = T> + MaybeSend + 'static,
T: MaybeSend + 'static,
{
Subscription::run_with((f, interval), |(f, interval)| {
let f = *f;
let interval = *interval;
stream::channel(1, move |mut output| async move {
loop {
let _ = output.send(f().await).await;
tokio::time::sleep(interval).await;
}
})
})
} }
} }

View file

@ -202,8 +202,8 @@ impl<T> Subscription<T> {
T: 'static, T: 'static,
{ {
from_recipe(Runner { from_recipe(Runner {
id: builder, data: builder,
spawn: move |_| builder(), spawn: |builder, _| builder(),
}) })
} }
@ -211,15 +211,15 @@ impl<T> Subscription<T> {
/// given [`Stream`]. /// given [`Stream`].
/// ///
/// The `id` will be used to uniquely identify the [`Subscription`]. /// The `id` will be used to uniquely identify the [`Subscription`].
pub fn run_with_id<I, S>(id: I, stream: S) -> Subscription<T> pub fn run_with<D, S>(data: D, builder: fn(&D) -> S) -> Self
where where
I: Hash + 'static, D: Hash + 'static,
S: Stream<Item = T> + MaybeSend + 'static, S: Stream<Item = T> + MaybeSend + 'static,
T: 'static, T: 'static,
{ {
from_recipe(Runner { from_recipe(Runner {
id, data: (data, builder),
spawn: move |_| stream, spawn: |(data, builder), _| builder(data),
}) })
} }
@ -423,8 +423,8 @@ where
T: 'static + MaybeSend, T: 'static + MaybeSend,
{ {
from_recipe(Runner { from_recipe(Runner {
id, data: id,
spawn: |events| { spawn: |_, events| {
use futures::future; use futures::future;
use futures::stream::StreamExt; use futures::stream::StreamExt;
@ -435,27 +435,27 @@ where
struct Runner<I, F, S, T> struct Runner<I, F, S, T>
where where
F: FnOnce(EventStream) -> S, F: FnOnce(&I, EventStream) -> S,
S: Stream<Item = T>, S: Stream<Item = T>,
{ {
id: I, data: I,
spawn: F, spawn: F,
} }
impl<I, F, S, T> Recipe for Runner<I, F, S, T> impl<I, F, S, T> Recipe for Runner<I, F, S, T>
where where
I: Hash + 'static, I: Hash + 'static,
F: FnOnce(EventStream) -> S, F: FnOnce(&I, EventStream) -> S,
S: Stream<Item = T> + MaybeSend + 'static, S: Stream<Item = T> + MaybeSend + 'static,
{ {
type Output = T; type Output = T;
fn hash(&self, state: &mut Hasher) { fn hash(&self, state: &mut Hasher) {
std::any::TypeId::of::<I>().hash(state); std::any::TypeId::of::<I>().hash(state);
self.id.hash(state); self.data.hash(state);
} }
fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> { fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> {
crate::boxed_stream((self.spawn)(input)) crate::boxed_stream((self.spawn)(&self.data, input))
} }
} }

View file

@ -365,9 +365,9 @@
//! //!
//! As with tasks, some modules expose convenient functions that build a [`Subscription`] for you—like //! As with tasks, some modules expose convenient functions that build a [`Subscription`] for you—like
//! [`time::every`] which can be used to listen to time, or [`keyboard::on_key_press`] which will notify you //! [`time::every`] which can be used to listen to time, or [`keyboard::on_key_press`] which will notify you
//! of any key presses. But you can also create your own with [`Subscription::run`] and [`run_with_id`]. //! of any key presses. But you can also create your own with [`Subscription::run`] and [`run_with`].
//! //!
//! [`run_with_id`]: Subscription::run_with_id //! [`run_with`]: Subscription::run_with
//! //!
//! ## Scaling Applications //! ## Scaling Applications
//! The `update`, `view`, and `Message` triplet composes very nicely. //! The `update`, `view`, and `Message` triplet composes very nicely.

View file

@ -1,5 +1,5 @@
//! Listen and react to time. //! Listen and react to time.
pub use crate::core::time::{Duration, Instant}; pub use crate::core::time::*;
#[allow(unused_imports)] #[allow(unused_imports)]
#[cfg_attr( #[cfg_attr(