futures::future

Trait FutureExt

Source
pub trait FutureExt: Future {
Show 26 methods // Provided methods fn map<U, F>(self, f: F) -> Map<Self, F> where F: FnOnce(Self::Item) -> U, Self: Sized { ... } fn map_err<E, F>(self, f: F) -> MapErr<Self, F> where F: FnOnce(Self::Error) -> E, Self: Sized { ... } fn err_into<E>(self) -> ErrInto<Self, E> where Self: Sized, Self::Error: Into<E> { ... } fn then<B, F>(self, f: F) -> Then<Self, B, F> where F: FnOnce(Result<Self::Item, Self::Error>) -> B, B: IntoFuture, Self: Sized { ... } fn and_then<B, F>(self, f: F) -> AndThen<Self, B, F> where F: FnOnce(Self::Item) -> B, B: IntoFuture<Error = Self::Error>, Self: Sized { ... } fn or_else<B, F>(self, f: F) -> OrElse<Self, B, F> where F: FnOnce(Self::Error) -> B, B: IntoFuture<Item = Self::Item>, Self: Sized { ... } fn select<B>(self, other: B) -> Select<Self, <B as IntoFuture>::Future> where B: IntoFuture, Self: Sized { ... } fn join<B>(self, other: B) -> Join<Self, <B as IntoFuture>::Future> where B: IntoFuture<Error = Self::Error>, Self: Sized { ... } fn join3<B, C>( self, b: B, c: C, ) -> Join3<Self, <B as IntoFuture>::Future, <C as IntoFuture>::Future> where B: IntoFuture<Error = Self::Error>, C: IntoFuture<Error = Self::Error>, Self: Sized { ... } fn join4<B, C, D>( self, b: B, c: C, d: D, ) -> Join4<Self, <B as IntoFuture>::Future, <C as IntoFuture>::Future, <D as IntoFuture>::Future> where B: IntoFuture<Error = Self::Error>, C: IntoFuture<Error = Self::Error>, D: IntoFuture<Error = Self::Error>, Self: Sized { ... } fn join5<B, C, D, E>( self, b: B, c: C, d: D, e: E, ) -> Join5<Self, <B as IntoFuture>::Future, <C as IntoFuture>::Future, <D as IntoFuture>::Future, <E as IntoFuture>::Future> where B: IntoFuture<Error = Self::Error>, C: IntoFuture<Error = Self::Error>, D: IntoFuture<Error = Self::Error>, E: IntoFuture<Error = Self::Error>, Self: Sized { ... } fn left<B>(self) -> Either<Self, B> where B: Future<Item = Self::Item, Error = Self::Error>, Self: Sized { ... } fn left_future<B>(self) -> Either<Self, B> where B: Future<Item = Self::Item, Error = Self::Error>, Self: Sized { ... } fn right<A>(self) -> Either<A, Self> where A: Future<Item = Self::Item, Error = Self::Error>, Self: Sized { ... } fn right_future<A>(self) -> Either<A, Self> where A: Future<Item = Self::Item, Error = Self::Error>, Self: Sized { ... } fn into_stream(self) -> IntoStream<Self> where Self: Sized { ... } fn flatten(self) -> Flatten<Self> where Self::Item: IntoFuture<Error = Self::Error>, Self: Sized { ... } fn flatten_sink(self) -> FlattenSink<Self> where Self::Item: Sink<SinkError = Self::Error>, Self: Sized { ... } fn flatten_stream(self) -> FlattenStream<Self> where Self::Item: Stream<Error = Self::Error>, Self: Sized { ... } fn fuse(self) -> Fuse<Self> where Self: Sized { ... } fn inspect<F>(self, f: F) -> Inspect<Self, F> where F: FnOnce(&Self::Item), Self: Sized { ... } fn inspect_err<F>(self, f: F) -> InspectErr<Self, F> where F: FnOnce(&Self::Error), Self: Sized { ... } fn catch_unwind(self) -> CatchUnwind<Self> where Self: Sized + UnwindSafe { ... } fn shared(self) -> Shared<Self> where Self: Sized { ... } fn recover<E, F>(self, f: F) -> Recover<Self, E, F> where Self: Sized, F: FnOnce(Self::Error) -> Self::Item { ... } fn with_executor<E>(self, executor: E) -> WithExecutor<Self, E> where Self: Sized, E: Executor { ... }
}
Expand description

An extension trait for Futures that provides a variety of convenient combinator functions.

Provided Methods§

Source

fn map<U, F>(self, f: F) -> Map<Self, F>
where F: FnOnce(Self::Item) -> U, Self: Sized,

Map this future’s result to a different type, returning a new future of the resulting type.

This function is similar to the Option::map or Iterator::map where it will change the type of the underlying future. This is useful to chain along a computation once a future has been resolved.

The closure provided will only be called if this future is resolved successfully. If this future returns an error, panics, or is dropped, then the closure provided will never be invoked.

Note that this function consumes the receiving future and returns a wrapped version of it, similar to the existing map methods in the standard library.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let future = future::ok::<u32, u32>(1);
let new_future = future.map(|x| x + 3);
assert_eq!(block_on(new_future), Ok(4));

Calling map on an errored Future has no effect:

use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let future = future::err::<u32, u32>(1);
let new_future = future.map(|x| x + 3);
assert_eq!(block_on(new_future), Err(1));
Source

fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
where F: FnOnce(Self::Error) -> E, Self: Sized,

Map this future’s error to a different error, returning a new future.

This function is similar to the Result::map_err where it will change the error type of the underlying future. This is useful for example to ensure that futures have the same error type when used with combinators like select and join.

The closure provided will only be called if this future is resolved with an error. If this future returns a success, panics, or is dropped, then the closure provided will never be invoked.

Note that this function consumes the receiving future and returns a wrapped version of it.

§Examples
use futures::future::err;
use futures::prelude::*;
use futures_executor::block_on;

let future = err::<u32, u32>(1);
let new_future = future.map_err(|x| x + 3);
assert_eq!(block_on(new_future), Err(4));

Calling map_err on a successful Future has no effect:

use futures::future::ok;
use futures::prelude::*;
use futures_executor::block_on;

let future = ok::<u32, u32>(1);
let new_future = future.map_err(|x| x + 3);
assert_eq!(block_on(new_future), Ok(1));
Source

fn err_into<E>(self) -> ErrInto<Self, E>
where Self: Sized, Self::Error: Into<E>,

Map this future’s error to a new error type using the Into trait.

This function does for futures what try! does for Result, by letting the compiler infer the type of the resulting error. Just as map_err above, this is useful for example to ensure that futures have the same error type when used with combinators like select and join.

Note that this function consumes the receiving future and returns a wrapped version of it.

§Examples
use futures::prelude::*;
use futures::future;

let future_with_err_u8 = future::err::<(), u8>(1);
let future_with_err_u32 = future_with_err_u8.err_into::<u32>();
Source

fn then<B, F>(self, f: F) -> Then<Self, B, F>
where F: FnOnce(Result<Self::Item, Self::Error>) -> B, B: IntoFuture, Self: Sized,

Chain on a computation for when a future finished, passing the result of the future to the provided closure f.

This function can be used to ensure a computation runs regardless of the conclusion of the future. The closure provided will be yielded a Result once the future is complete.

The returned value of the closure must implement the IntoFuture trait and can represent some more work to be done before the composed future is finished. Note that the Result type implements the IntoFuture trait so it is possible to simply alter the Result yielded to the closure and return it.

If this future is dropped or panics then the closure f will not be run.

Note that this function consumes the receiving future and returns a wrapped version of it.

§Examples
use futures::prelude::*;
use futures::future;

let future_of_1 = future::ok::<u32, u32>(1);
let future_of_4 = future_of_1.then(|x| {
    x.map(|y| y + 3)
});

let future_of_err_1 = future::err::<u32, u32>(1);
let future_of_4 = future_of_err_1.then(|x| {
    match x {
        Ok(_) => panic!("expected an error"),
        Err(y) => future::ok::<u32, u32>(y + 3),
    }
});
Source

fn and_then<B, F>(self, f: F) -> AndThen<Self, B, F>
where F: FnOnce(Self::Item) -> B, B: IntoFuture<Error = Self::Error>, Self: Sized,

Execute another future after this one has resolved successfully.

This function can be used to chain two futures together and ensure that the final future isn’t resolved until both have finished. The closure provided is yielded the successful result of this future and returns another value which can be converted into a future.

Note that because Result implements the IntoFuture trait this method can also be useful for chaining fallible and serial computations onto the end of one future.

If this future is dropped, panics, or completes with an error then the provided closure f is never called.

Note that this function consumes the receiving future and returns a wrapped version of it.

§Examples
use futures::prelude::*;
use futures::future::{self, FutureResult};

let future_of_1 = future::ok::<u32, u32>(1);
let future_of_4 = future_of_1.and_then(|x| {
    Ok(x + 3)
});

let future_of_err_1 = future::err::<u32, u32>(1);
future_of_err_1.and_then(|_| -> FutureResult<u32, u32> {
    panic!("should not be called in case of an error");
});
Source

fn or_else<B, F>(self, f: F) -> OrElse<Self, B, F>
where F: FnOnce(Self::Error) -> B, B: IntoFuture<Item = Self::Item>, Self: Sized,

Execute another future if this one resolves with an error.

Return a future that passes along this future’s value if it succeeds, and otherwise passes the error to the closure f and waits for the future it returns. The closure may also simply return a value that can be converted into a future.

Note that because Result implements the IntoFuture trait this method can also be useful for chaining together fallback computations, where when one fails, the next is attempted.

If this future is dropped, panics, or completes successfully then the provided closure f is never called.

Note that this function consumes the receiving future and returns a wrapped version of it.

§Examples
use futures::prelude::*;
use futures::future::{self, FutureResult};

let future_of_err_1 = future::err::<u32, u32>(1);
let future_of_4 = future_of_err_1.or_else(|x| -> Result<u32, u32> {
    Ok(x + 3)
});

let future_of_1 = future::ok::<u32, u32>(1);
future_of_1.or_else(|_| -> FutureResult<u32, u32> {
    panic!("should not be called in case of success");
});
Source

fn select<B>(self, other: B) -> Select<Self, <B as IntoFuture>::Future>
where B: IntoFuture, Self: Sized,

Waits for either one of two differently-typed futures to complete.

This function will return a new future which awaits for either this or the other future to complete. The returned future will finish with both the value resolved and a future representing the completion of the other work.

Note that this function consumes the receiving futures and returns a wrapped version of them.

Also note that if both this and the second future have the same success/error type you can use the Either::split method to conveniently extract out the value at the end.

§Examples
use futures::prelude::*;
use futures::future::{self, Either};

// A poor-man's join implemented on top of select

fn join<A, B, E>(a: A, b: B) -> Box<Future<Item=(A::Item, B::Item), Error=E>>
    where A: Future<Error = E> + 'static,
          B: Future<Error = E> + 'static,
          E: 'static,
{
    Box::new(a.select(b).then(|res| -> Box<Future<Item=_, Error=_>> {
        match res {
            Ok(Either::Left((x, b))) => Box::new(b.map(move |y| (x, y))),
            Ok(Either::Right((y, a))) => Box::new(a.map(move |x| (x, y))),
            Err(Either::Left((e, _))) => Box::new(future::err(e)),
            Err(Either::Right((e, _))) => Box::new(future::err(e)),
        }
    }))
}
Source

fn join<B>(self, other: B) -> Join<Self, <B as IntoFuture>::Future>
where B: IntoFuture<Error = Self::Error>, Self: Sized,

Joins the result of two futures, waiting for them both to complete.

This function will return a new future which awaits both this and the other future to complete. The returned future will finish with a tuple of both results.

Both futures must have the same error type, and if either finishes with an error then the other will be dropped and that error will be returned.

Note that this function consumes the receiving future and returns a wrapped version of it.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let a = future::ok::<u32, u32>(1);
let b = future::ok::<u32, u32>(2);
let pair = a.join(b);

assert_eq!(block_on(pair), Ok((1, 2)));

If one or both of the joined Futures is errored, the resulting Future will be errored:

use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let a = future::ok::<u32, u32>(1);
let b = future::err::<u32, u32>(2);
let pair = a.join(b);

assert_eq!(block_on(pair), Err(2));
Source

fn join3<B, C>( self, b: B, c: C, ) -> Join3<Self, <B as IntoFuture>::Future, <C as IntoFuture>::Future>
where B: IntoFuture<Error = Self::Error>, C: IntoFuture<Error = Self::Error>, Self: Sized,

Same as join, but with more futures.

Source

fn join4<B, C, D>( self, b: B, c: C, d: D, ) -> Join4<Self, <B as IntoFuture>::Future, <C as IntoFuture>::Future, <D as IntoFuture>::Future>
where B: IntoFuture<Error = Self::Error>, C: IntoFuture<Error = Self::Error>, D: IntoFuture<Error = Self::Error>, Self: Sized,

Same as join, but with more futures.

Source

fn join5<B, C, D, E>( self, b: B, c: C, d: D, e: E, ) -> Join5<Self, <B as IntoFuture>::Future, <C as IntoFuture>::Future, <D as IntoFuture>::Future, <E as IntoFuture>::Future>
where B: IntoFuture<Error = Self::Error>, C: IntoFuture<Error = Self::Error>, D: IntoFuture<Error = Self::Error>, E: IntoFuture<Error = Self::Error>, Self: Sized,

Same as join, but with more futures.

Source

fn left<B>(self) -> Either<Self, B>
where B: Future<Item = Self::Item, Error = Self::Error>, Self: Sized,

👎Deprecated: use left_future instead

Wrap this future in an Either future, making it the left-hand variant of that Either.

This can be used in combination with the right method to write if statements that evaluate to different futures in different branches.

§Examples
use futures::executor::block_on;
use futures::future::*;

let x = 6;
let future = if x < 10 {
    ok::<_, bool>(x).left()
} else {
    empty().right()
};

assert_eq!(x, block_on(future).unwrap());
Source

fn left_future<B>(self) -> Either<Self, B>
where B: Future<Item = Self::Item, Error = Self::Error>, Self: Sized,

Wrap this future in an Either future, making it the left-hand variant of that Either.

This can be used in combination with the right_future method to write if statements that evaluate to different futures in different branches.

§Examples
use futures::executor::block_on;
use futures::future::*;

let x = 6;
let future = if x < 10 {
    ok::<_, bool>(x).left_future()
} else {
    empty().right_future()
};

assert_eq!(x, block_on(future).unwrap());
Source

fn right<A>(self) -> Either<A, Self>
where A: Future<Item = Self::Item, Error = Self::Error>, Self: Sized,

👎Deprecated: use right_future instead

Wrap this future in an Either future, making it the right-hand variant of that Either.

This can be used in combination with the left_future method to write if statements that evaluate to different futures in different branches.

§Examples
use futures::executor::block_on;
use futures::future::*;

let x = 6;
let future = if x < 10 {
    ok::<_, bool>(x).left()
} else {
    empty().right()
};

assert_eq!(x, block_on(future).unwrap());
Source

fn right_future<A>(self) -> Either<A, Self>
where A: Future<Item = Self::Item, Error = Self::Error>, Self: Sized,

Wrap this future in an Either future, making it the right-hand variant of that Either.

This can be used in combination with the left_future method to write if statements that evaluate to different futures in different branches.

§Examples
use futures::executor::block_on;
use futures::future::*;

let x = 6;
let future = if x < 10 {
    ok::<_, bool>(x).left_future()
} else {
    empty().right_future()
};

assert_eq!(x, block_on(future).unwrap());
Source

fn into_stream(self) -> IntoStream<Self>
where Self: Sized,

Convert this future into a single element stream.

The returned stream contains single success if this future resolves to success or single error if this future resolves into error.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let future = future::ok::<_, bool>(17);
let stream = future.into_stream();
let collected: Vec<_> = block_on(stream.collect()).unwrap();
assert_eq!(collected, vec![17]);

let future = future::err::<bool, _>(19);
let stream = future.into_stream();
let collected: Result<Vec<_>, _> = block_on(stream.collect());
assert_eq!(collected, Err(19));
Source

fn flatten(self) -> Flatten<Self>
where Self::Item: IntoFuture<Error = Self::Error>, Self: Sized,

Flatten the execution of this future when the successful result of this future is itself another future.

This can be useful when combining futures together to flatten the computation out the final result. This method can only be called when the successful result of this future itself implements the IntoFuture trait and the error can be created from this future’s error type.

This method is roughly equivalent to self.and_then(|x| x).

Note that this function consumes the receiving future and returns a wrapped version of it.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let nested_future = future::ok::<_, u32>(future::ok::<u32, u32>(1));
let future = nested_future.flatten();
assert_eq!(block_on(future), Ok(1));

Calling flatten on an errored Future, or if the inner Future is errored, will result in an errored Future:

use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let nested_future = future::ok::<_, u32>(future::err::<u32, u32>(1));
let future = nested_future.flatten();
assert_eq!(block_on(future), Err(1));
Source

fn flatten_sink(self) -> FlattenSink<Self>
where Self::Item: Sink<SinkError = Self::Error>, Self: Sized,

Flatten the execution of this future when the successful result of this future is a sink.

This can be useful when sink initialization is deferred, and it is convenient to work with that sink as if sink was available at the call site.

Note that this function consumes this future and returns a wrapped version of it.

Source

fn flatten_stream(self) -> FlattenStream<Self>
where Self::Item: Stream<Error = Self::Error>, Self: Sized,

Flatten the execution of this future when the successful result of this future is a stream.

This can be useful when stream initialization is deferred, and it is convenient to work with that stream as if stream was available at the call site.

Note that this function consumes this future and returns a wrapped version of it.

§Examples
use futures::prelude::*;
use futures::future;
use futures::stream;
use futures_executor::block_on;

let stream_items = vec![17, 18, 19];
let future_of_a_stream = future::ok::<_, bool>(stream::iter_ok(stream_items));

let stream = future_of_a_stream.flatten_stream();
let list: Vec<_> = block_on(stream.collect()).unwrap();
assert_eq!(list, vec![17, 18, 19]);
Source

fn fuse(self) -> Fuse<Self>
where Self: Sized,

Fuse a future such that poll will never again be called once it has completed.

Currently once a future has returned Ready or Err from poll any further calls could exhibit bad behavior such as blocking forever, panicking, never returning, etc. If it is known that poll may be called too often then this method can be used to ensure that it has defined semantics.

Once a future has been fused and it returns a completion from poll, then it will forever return Pending from poll again (never resolve). This, unlike the trait’s poll method, is guaranteed.

This combinator will drop this future as soon as it’s been completed to ensure resources are reclaimed as soon as possible.

Source

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where F: FnOnce(&Self::Item), Self: Sized,

Do something with the item of a future, passing it on.

When using futures, you’ll often chain several of them together. While working on such code, you might want to check out what’s happening at various parts in the pipeline. To do that, insert a call to inspect.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let future = future::ok::<u32, u32>(1);
let new_future = future.inspect(|&x| println!("about to resolve: {}", x));
assert_eq!(block_on(new_future), Ok(1));
Source

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where F: FnOnce(&Self::Error), Self: Sized,

Do something with the error of a future, passing it on.

When using futures, you’ll often chain several of them together. While working on such code, you might want to check out what’s happening to the errors at various parts in the pipeline. To do that, insert a call to inspect_err.

§Examples
use futures::prelude::*;
use futures::future;
use futures::executor::block_on;

let future = future::err::<u32, u32>(1);
let new_future = future.inspect_err(|&x| println!("about to error: {}", x));
assert_eq!(block_on(new_future), Err(1));
Source

fn catch_unwind(self) -> CatchUnwind<Self>
where Self: Sized + UnwindSafe,

Catches unwinding panics while polling the future.

In general, panics within a future can propagate all the way out to the task level. This combinator makes it possible to halt unwinding within the future itself. It’s most commonly used within task executors. It’s not recommended to use this for error handling.

Note that this method requires the UnwindSafe bound from the standard library. This isn’t always applied automatically, and the standard library provides an AssertUnwindSafe wrapper type to apply it after-the fact. To assist using this method, the Future trait is also implemented for AssertUnwindSafe<F> where F implements Future.

This method is only available when the std feature of this library is activated, and it is activated by default.

§Examples
use futures::prelude::*;
use futures::future::{self, FutureResult};
use futures_executor::block_on;

let mut future = future::ok::<i32, u32>(2);
assert!(block_on(future.catch_unwind()).is_ok());

let mut future = future::lazy(|_| -> FutureResult<i32, u32> {
    panic!();
    future::ok::<i32, u32>(2)
});
assert!(block_on(future.catch_unwind()).is_err());
Source

fn shared(self) -> Shared<Self>
where Self: Sized,

Create a cloneable handle to this future where all handles will resolve to the same result.

The shared() method provides a method to convert any future into a cloneable future. It enables a future to be polled by multiple threads.

The returned Shared future resolves successfully with SharedItem<Self::Item> or erroneously with SharedError<Self::Error>. Both SharedItem and SharedError implements Deref to allow shared access to the underlying result. Ownership of Self::Item and Self::Error cannot currently be reclaimed.

This method is only available when the std feature of this library is activated, and it is activated by default.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let future = future::ok::<_, bool>(6);
let shared1 = future.shared();
let shared2 = shared1.clone();

assert_eq!(6, *block_on(shared1).unwrap());
assert_eq!(6, *block_on(shared2).unwrap());
use std::thread;

use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let future = future::ok::<_, bool>(6);
let shared1 = future.shared();
let shared2 = shared1.clone();
let join_handle = thread::spawn(move || {
    assert_eq!(6, *block_on(shared2).unwrap());
});
assert_eq!(6, *block_on(shared1).unwrap());
join_handle.join().unwrap();
Source

fn recover<E, F>(self, f: F) -> Recover<Self, E, F>
where Self: Sized, F: FnOnce(Self::Error) -> Self::Item,

Handle errors generated by this future by converting them into Self::Item.

Because it can never produce an error, the returned Recover future can conform to any specific Error type, including Never.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::block_on;

let future = future::err::<(), &str>("something went wrong");
let new_future = future.recover::<Never, _>(|_| ());
assert_eq!(block_on(new_future), Ok(()));
Source

fn with_executor<E>(self, executor: E) -> WithExecutor<Self, E>
where Self: Sized, E: Executor,

Assigns the provided Executor to be used when spawning tasks from within the future.

§Examples
use futures::prelude::*;
use futures::future;
use futures_executor::{block_on, spawn, ThreadPool};

let pool = ThreadPool::new().expect("unable to create threadpool");
let future = future::ok::<(), _>(());
let spawn_future = spawn(future).with_executor(pool);
assert_eq!(block_on(spawn_future), Ok(()));

Implementors§

Source§

impl<T> FutureExt for T
where T: Future + ?Sized,