Skip to content

Commit 6dc39b0

Browse files
committed
Add Fuse::terminated constructor
1 parent 4284055 commit 6dc39b0

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

futures-util/src/future/fuse.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,56 @@ impl<Fut: Future> Fuse<Fut> {
1818
future: Some(f),
1919
}
2020
}
21+
22+
/// Creates a new `Fuse`-wrapped future which is already terminated.
23+
///
24+
/// This can be useful in combination with looping and the `select!`
25+
/// macro, which bypasses terminated futures.
26+
///
27+
/// # Examples
28+
///
29+
/// ```
30+
/// #![feature(async_await, await_macro, futures_api)]
31+
/// # futures::executor::block_on(async {
32+
/// use futures::channel::mpsc;
33+
/// use futures::future::{Fuse, FusedFuture, FutureExt};
34+
/// use futures::select;
35+
/// use futures::stream::StreamExt;
36+
/// use pin_utils::pin_mut;
37+
///
38+
/// let (sender, mut stream) = mpsc::unbounded();
39+
///
40+
/// // Send a few messages into the stream
41+
/// sender.unbounded_send(()).unwrap();
42+
/// sender.unbounded_send(()).unwrap();
43+
/// drop(sender);
44+
///
45+
/// // Use `Fuse::termianted()` to create an already-terminated future
46+
/// // which may be instantiated later.
47+
/// let foo_printer = Fuse::terminated();
48+
/// pin_mut!(foo_printer);
49+
///
50+
/// loop {
51+
/// select! {
52+
/// _ = foo_printer => {},
53+
/// () = stream.select_next_some() => {
54+
/// if !foo_printer.is_terminated() {
55+
/// println!("Foo is already being printed!");
56+
/// } else {
57+
/// foo_printer.set(async {
58+
/// // do some other async operations
59+
/// println!("Printing foo from `foo_printer` future");
60+
/// }.fuse());
61+
/// }
62+
/// },
63+
/// complete => break, // `foo_printer` is terminated and the stream is done
64+
/// }
65+
/// }
66+
/// # });
67+
/// ```
68+
pub fn terminated() -> Fuse<Fut> {
69+
Fuse { future: None }
70+
}
2171
}
2272

2373
impl<Fut: Future> FusedFuture for Fuse<Fut> {

0 commit comments

Comments
 (0)