Draft first version of event subscriptions 🎉

This commit is contained in:
Héctor Ramón Jiménez 2019-12-05 06:10:13 +01:00
parent e92ea48e88
commit d575f45411
11 changed files with 182 additions and 12 deletions

View file

@ -9,7 +9,7 @@
//! [Iced]: https://github.com/hecrj/iced
//! [`iced_native`]: https://github.com/hecrj/iced/tree/master/native
//! [`iced_web`]: https://github.com/hecrj/iced/tree/master/web
#![deny(missing_docs)]
//#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(unused_results)]
#![deny(unsafe_code)]
@ -38,3 +38,9 @@ mod command;
#[cfg(feature = "command")]
pub use command::Command;
#[cfg(feature = "subscription")]
pub mod subscription;
#[cfg(feature = "subscription")]
pub use subscription::Subscription;

61
core/src/subscription.rs Normal file
View file

@ -0,0 +1,61 @@
//! Generate events asynchronously for you application.
/// An event subscription.
pub struct Subscription<T> {
definitions: Vec<Box<dyn Definition<Message = T>>>,
}
impl<T> Subscription<T> {
pub fn none() -> Self {
Self {
definitions: Vec::new(),
}
}
pub fn batch(subscriptions: impl Iterator<Item = Subscription<T>>) -> Self {
Self {
definitions: subscriptions
.flat_map(|subscription| subscription.definitions)
.collect(),
}
}
pub fn definitions(self) -> Vec<Box<dyn Definition<Message = T>>> {
self.definitions
}
}
impl<T, A> From<A> for Subscription<T>
where
A: Definition<Message = T> + 'static,
{
fn from(definition: A) -> Self {
Self {
definitions: vec![Box::new(definition)],
}
}
}
/// The definition of an event subscription.
pub trait Definition {
type Message;
fn id(&self) -> u64;
fn stream(
&self,
) -> (
futures::stream::BoxStream<'static, Self::Message>,
Box<dyn Handle>,
);
}
pub trait Handle {
fn cancel(&mut self);
}
impl<T> std::fmt::Debug for Subscription<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Command").finish()
}
}