Implement time::repeat and simplify Subscription::run_with

This commit is contained in:
Héctor Ramón Jiménez 2025-01-24 16:38:56 +01:00
parent 75a6f32a5e
commit 3a07c631ad
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
3 changed files with 48 additions and 42 deletions

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.