Implement future-based Command in iced_core

This commit is contained in:
Héctor Ramón Jiménez 2019-11-17 07:02:38 +01:00
parent 2cbd5d60c4
commit e0bdb203f2
5 changed files with 62 additions and 2 deletions

View File

@ -6,3 +6,10 @@ edition = "2018"
description = "The essential concepts of Iced" description = "The essential concepts of Iced"
license = "MIT" license = "MIT"
repository = "https://github.com/hecrj/iced" repository = "https://github.com/hecrj/iced"
[features]
# Exposes a future-based `Command` type
command = ["futures"]
[dependencies]
futures = { version = "0.3", optional = true }

49
core/src/command.rs Normal file
View File

@ -0,0 +1,49 @@
use futures::future::{BoxFuture, Future, FutureExt};
pub struct Command<T> {
futures: Vec<BoxFuture<'static, T>>,
}
impl<T> Command<T> {
pub fn none() -> Self {
Self {
futures: Vec::new(),
}
}
pub fn attempt<A>(
future: impl Future<Output = T> + 'static + Send,
f: impl Fn(T) -> A + 'static + Send,
) -> Command<A> {
Command {
futures: vec![future.map(f).boxed()],
}
}
pub fn batch(commands: impl Iterator<Item = Command<T>>) -> Self {
Self {
futures: commands.flat_map(|command| command.futures).collect(),
}
}
pub fn futures(self) -> Vec<BoxFuture<'static, T>> {
self.futures
}
}
impl<T, A> From<A> for Command<T>
where
A: Future<Output = T> + 'static + Send,
{
fn from(future: A) -> Self {
Self {
futures: vec![future.boxed()],
}
}
}
impl<T> std::fmt::Debug for Command<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Command").finish()
}
}

View File

@ -3,6 +3,8 @@ pub mod widget;
mod align; mod align;
mod background; mod background;
mod color; mod color;
#[cfg(feature = "command")]
mod command;
mod font; mod font;
mod length; mod length;
mod point; mod point;
@ -12,6 +14,8 @@ mod vector;
pub use align::Align; pub use align::Align;
pub use background::Background; pub use background::Background;
pub use color::Color; pub use color::Color;
#[cfg(feature = "command")]
pub use command::Command;
pub use font::Font; pub use font::Font;
pub use length::Length; pub use length::Length;
pub use point::Point; pub use point::Point;

View File

@ -8,6 +8,6 @@ license = "MIT"
repository = "https://github.com/hecrj/iced" repository = "https://github.com/hecrj/iced"
[dependencies] [dependencies]
iced_core = { version = "0.1.0-alpha", path = "../core" } iced_core = { version = "0.1.0-alpha", path = "../core", features = ["command"] }
twox-hash = "1.5" twox-hash = "1.5"
raw-window-handle = "0.3" raw-window-handle = "0.3"

View File

@ -216,7 +216,7 @@ mod size;
mod user_interface; mod user_interface;
pub use iced_core::{ pub use iced_core::{
Align, Background, Color, Font, Length, Point, Rectangle, Vector, Align, Background, Color, Command, Font, Length, Point, Rectangle, Vector,
}; };
pub use element::Element; pub use element::Element;