From d50ff9b5d97d9c3d6c6c70a9b4efe764b6126c86 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sun, 19 Jan 2020 09:06:48 +0100 Subject: Implement `Runtime` and `Executor` in `iced_core` They can be leveraged by shells to easily execute commands and track subscriptions. --- core/src/runtime.rs | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 core/src/runtime.rs (limited to 'core/src/runtime.rs') diff --git a/core/src/runtime.rs b/core/src/runtime.rs new file mode 100644 index 00000000..31234d11 --- /dev/null +++ b/core/src/runtime.rs @@ -0,0 +1,74 @@ +mod executor; + +pub use executor::Executor; + +use crate::{subscription, Command, Subscription}; + +use futures::Sink; +use std::marker::PhantomData; + +#[derive(Debug)] +pub struct Runtime { + executor: Executor, + subscriptions: subscription::Tracker, + receiver: Receiver, + _message: PhantomData, +} + +impl + Runtime +where + Hasher: std::hash::Hasher + Default, + Event: Send + Clone + 'static, + Executor: self::Executor, + Receiver: Sink + + Unpin + + Send + + Clone + + 'static, + Message: Send + 'static, +{ + pub fn new(receiver: Receiver) -> Self { + Self { + executor: Executor::new(), + subscriptions: subscription::Tracker::new(), + receiver, + _message: PhantomData, + } + } + + pub fn spawn(&mut self, command: Command) { + use futures::{FutureExt, SinkExt}; + + let futures = command.futures(); + + for future in futures { + let mut receiver = self.receiver.clone(); + + self.executor.spawn(future.then(|message| { + async move { + let _ = receiver.send(message).await; + + () + } + })); + } + } + + pub fn track( + &mut self, + subscription: Subscription, + ) { + let futures = self + .subscriptions + .update(subscription, self.receiver.clone()); + + for future in futures { + self.executor.spawn(future); + } + } + + pub fn broadcast(&mut self, event: Event) { + self.subscriptions.broadcast(event); + } +} -- cgit