Skip to content

Commit

Permalink
Introduce Task::abortable 🎉
Browse files Browse the repository at this point in the history
  • Loading branch information
hecrj committed Jul 10, 2024
1 parent 8efe161 commit 49f4c5f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
37 changes: 37 additions & 0 deletions runtime/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,21 @@ impl<T> Task<T> {
}
}

/// Creates a new [`Task`] that can be aborted with the returned [`Handle`].
pub fn abortable(self) -> (Self, Handle)
where
T: 'static,
{
match self.0 {
Some(stream) => {
let (stream, handle) = stream::abortable(stream);

(Self(Some(boxed_stream(stream))), Handle(Some(handle)))
}
None => (Self(None), Handle(None)),
}
}

/// Creates a new [`Task`] that runs the given [`Future`] and produces
/// its output.
pub fn future(future: impl Future<Output = T> + MaybeSend + 'static) -> Self
Expand All @@ -178,6 +193,28 @@ impl<T> Task<T> {
}
}

/// A handle to a [`Task`] that can be used for aborting it.
#[derive(Debug, Clone)]
pub struct Handle(Option<stream::AbortHandle>);

impl Handle {
/// Aborts the [`Task`] of this [`Handle`].
pub fn abort(&self) {
if let Some(handle) = &self.0 {
handle.abort()

Check failure on line 204 in runtime/src/task.rs

View workflow job for this annotation

GitHub Actions / all

consider adding a `;` to the last statement for consistent formatting

Check failure on line 204 in runtime/src/task.rs

View workflow job for this annotation

GitHub Actions / all

consider adding a `;` to the last statement for consistent formatting
}
}

/// Returns `true` if the [`Task`] of this [`Handle`] has been aborted.
pub fn is_aborted(&self) -> bool {
if let Some(handle) = &self.0 {
handle.is_aborted()
} else {
true
}
}
}

impl<T> Task<Option<T>> {
/// Executes a new [`Task`] after this one, only when it produces `Some` value.
///
Expand Down
8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,14 @@ pub use crate::core::{
Length, Padding, Pixels, Point, Radians, Rectangle, Rotation, Shadow, Size,
Theme, Transformation, Vector,
};
pub use crate::runtime::{exit, Task};
pub use crate::runtime::exit;
pub use iced_futures::Subscription;

pub mod task {
//! Create runtime tasks.
pub use crate::runtime::task::{Handle, Task};
}

pub mod clipboard {
//! Access the clipboard.
pub use crate::runtime::clipboard::{
Expand Down Expand Up @@ -309,6 +314,7 @@ pub use executor::Executor;
pub use font::Font;
pub use renderer::Renderer;
pub use settings::Settings;
pub use task::Task;

#[doc(inline)]
pub use application::application;
Expand Down

0 comments on commit 49f4c5f

Please sign in to comment.