Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BlockAwait trait #2803

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion futures-executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@
#[cfg(feature = "std")]
mod local_pool;
#[cfg(feature = "std")]
pub use crate::local_pool::{block_on, block_on_stream, BlockingStream, LocalPool, LocalSpawner};
pub use crate::local_pool::{
block_on, block_on_stream, BlockAwait, BlockingStream, LocalPool, LocalSpawner,
};

#[cfg(feature = "thread-pool")]
#[cfg_attr(docsrs, doc(cfg(feature = "thread-pool")))]
Expand Down
19 changes: 19 additions & 0 deletions futures-executor/src/local_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,25 @@ pub fn block_on_stream<S: Stream + Unpin>(stream: S) -> BlockingStream<S> {
BlockingStream { stream }
}

/// A trait for awaiting a future in a non-async context. This is automatically implemented for anything implementing [`Future`].
///
/// This functions the same as [`block_on`], but allows for a chaining style similar to `.await` syntax.
pub trait BlockAwait<F: Future> {
/// The output of running the future.
type Output;

/// Block until the future completes by passing the future to [`block_on`].
fn block_await(self) -> Self::Output;
}

impl<F: Future> BlockAwait<F> for F {
type Output = F::Output;

fn block_await(self) -> Self::Output {
block_on(self)
}
}

/// An iterator which blocks on values from a stream until they become available.
#[derive(Debug)]
pub struct BlockingStream<S: Stream + Unpin> {
Expand Down
2 changes: 1 addition & 1 deletion futures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ pub mod executor {
//! [`spawn_local_obj`]: https://docs.rs/futures/0.3/futures/task/trait.LocalSpawn.html#tymethod.spawn_local_obj

pub use futures_executor::{
block_on, block_on_stream, enter, BlockingStream, Enter, EnterError, LocalPool,
block_on, block_on_stream, enter, BlockAwait, BlockingStream, Enter, EnterError, LocalPool,
LocalSpawner,
};

Expand Down