Trait futures_util::stream::TryStreamExt

source ·
pub trait TryStreamExt: TryStream {
Show 21 methods // Provided methods fn err_into<E>(self) -> ErrInto<Self, E> where Self: Sized, Self::Error: Into<E> { ... } fn map_ok<T, F>(self, f: F) -> MapOk<Self, F> where Self: Sized, F: FnMut(Self::Ok) -> T { ... } fn map_err<E, F>(self, f: F) -> MapErr<Self, F> where Self: Sized, F: FnMut(Self::Error) -> E { ... } fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F> where F: FnMut(Self::Ok) -> Fut, Fut: TryFuture<Error = Self::Error>, Self: Sized { ... } fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F> where F: FnMut(Self::Error) -> Fut, Fut: TryFuture<Ok = Self::Ok>, Self: Sized { ... } fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F> where F: FnMut(&Self::Ok), Self: Sized { ... } fn inspect_err<F>(self, f: F) -> InspectErr<Self, F> where F: FnMut(&Self::Error), Self: Sized { ... } fn into_stream(self) -> IntoStream<Self> where Self: Sized { ... } fn try_next(&mut self) -> TryNext<'_, Self> where Self: Unpin { ... } fn try_for_each<Fut, F>(self, f: F) -> TryForEach<Self, Fut, F> where F: FnMut(Self::Ok) -> Fut, Fut: TryFuture<Ok = (), Error = Self::Error>, Self: Sized { ... } fn try_skip_while<Fut, F>(self, f: F) -> TrySkipWhile<Self, Fut, F> where F: FnMut(&Self::Ok) -> Fut, Fut: TryFuture<Ok = bool, Error = Self::Error>, Self: Sized { ... } fn try_take_while<Fut, F>(self, f: F) -> TryTakeWhile<Self, Fut, F> where F: FnMut(&Self::Ok) -> Fut, Fut: TryFuture<Ok = bool, Error = Self::Error>, Self: Sized { ... } fn try_collect<C: Default + Extend<Self::Ok>>(self) -> TryCollect<Self, C> where Self: Sized { ... } fn try_filter<Fut, F>(self, f: F) -> TryFilter<Self, Fut, F> where Fut: Future<Output = bool>, F: FnMut(&Self::Ok) -> Fut, Self: Sized { ... } fn try_filter_map<Fut, F, T>(self, f: F) -> TryFilterMap<Self, Fut, F> where Fut: TryFuture<Ok = Option<T>, Error = Self::Error>, F: FnMut(Self::Ok) -> Fut, Self: Sized { ... } fn try_flatten(self) -> TryFlatten<Self> where Self::Ok: TryStream, <Self::Ok as TryStream>::Error: From<Self::Error>, Self: Sized { ... } fn try_fold<T, Fut, F>(self, init: T, f: F) -> TryFold<Self, Fut, T, F> where F: FnMut(T, Self::Ok) -> Fut, Fut: TryFuture<Ok = T, Error = Self::Error>, Self: Sized { ... } fn try_concat(self) -> TryConcat<Self> where Self: Sized, Self::Ok: Extend<<<Self as TryStream>::Ok as IntoIterator>::Item> + IntoIterator + Default { ... } fn try_poll_next_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Option<Result<Self::Ok, Self::Error>>> where Self: Unpin { ... } fn try_all<Fut, F>(self, f: F) -> TryAll<Self, Fut, F> where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future<Output = bool> { ... } fn try_any<Fut, F>(self, f: F) -> TryAny<Self, Fut, F> where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future<Output = bool> { ... }
}
Expand description

Adapters specific to Result-returning streams

Provided Methods§

source

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

Wraps the current stream in a new stream which converts the error type into the one provided.

§Examples
use futures::stream::{self, TryStreamExt};

let mut stream =
    stream::iter(vec![Ok(()), Err(5i32)])
        .err_into::<i64>();

assert_eq!(stream.try_next().await, Ok(Some(())));
assert_eq!(stream.try_next().await, Err(5i64));
source

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where Self: Sized, F: FnMut(Self::Ok) -> T,

Wraps the current stream in a new stream which maps the success value using the provided closure.

§Examples
use futures::stream::{self, TryStreamExt};

let mut stream =
    stream::iter(vec![Ok(5), Err(0)])
        .map_ok(|x| x + 2);

assert_eq!(stream.try_next().await, Ok(Some(7)));
assert_eq!(stream.try_next().await, Err(0));
source

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

Wraps the current stream in a new stream which maps the error value using the provided closure.

§Examples
use futures::stream::{self, TryStreamExt};

let mut stream =
    stream::iter(vec![Ok(5), Err(0)])
        .map_err(|x| x + 2);

assert_eq!(stream.try_next().await, Ok(Some(5)));
assert_eq!(stream.try_next().await, Err(2));
source

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where F: FnMut(Self::Ok) -> Fut, Fut: TryFuture<Error = Self::Error>, Self: Sized,

Chain on a computation for when a value is ready, passing the successful results to the provided closure f.

This function can be used to run a unit of work when the next successful value on a stream is ready. The closure provided will be yielded a value when ready, and the returned future will then be run to completion to produce the next value on this stream.

Any errors produced by this stream will not be passed to the closure, and will be passed through.

The returned value of the closure must implement the TryFuture trait and can represent some more work to be done before the composed stream is finished.

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

To process the entire stream and return a single future representing success or error, use try_for_each instead.

§Examples
use futures::channel::mpsc;
use futures::future;
use futures::stream::TryStreamExt;

let (_tx, rx) = mpsc::channel::<Result<i32, ()>>(1);

let rx = rx.and_then(|result| {
    future::ok(if result % 2 == 0 {
        Some(result)
    } else {
        None
    })
});
source

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
where F: FnMut(Self::Error) -> Fut, Fut: TryFuture<Ok = Self::Ok>, Self: Sized,

Chain on a computation for when an error happens, passing the erroneous result to the provided closure f.

This function can be used to run a unit of work and attempt to recover from an error if one happens. The closure provided will be yielded an error when one appears, and the returned future will then be run to completion to produce the next value on this stream.

Any successful values produced by this stream will not be passed to the closure, and will be passed through.

The returned value of the closure must implement the TryFuture trait and can represent some more work to be done before the composed stream is finished.

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

source

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where F: FnMut(&Self::Ok), Self: Sized,

Do something with the success value of this stream, afterwards passing it on.

This is similar to the StreamExt::inspect method where it allows easily inspecting the success value as it passes through the stream, for example to debug what’s going on.

source

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

Do something with the error value of this stream, afterwards passing it on.

This is similar to the StreamExt::inspect method where it allows easily inspecting the error value as it passes through the stream, for example to debug what’s going on.

source

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

Wraps a TryStream into a type that implements Stream

TryStreams currently do not implement the Stream trait because of limitations of the compiler.

§Examples
use futures::stream::{Stream, TryStream, TryStreamExt};

fn make_try_stream() -> impl TryStream<Ok = T, Error = E> { // ... }
fn take_stream(stream: impl Stream<Item = Result<T, E>>) { /* ... */ }

take_stream(make_try_stream().into_stream());
source

fn try_next(&mut self) -> TryNext<'_, Self>
where Self: Unpin,

Creates a future that attempts to resolve the next item in the stream. If an error is encountered before the next item, the error is returned instead.

This is similar to the Stream::next combinator, but returns a Result<Option<T>, E> rather than an Option<Result<T, E>>, making for easy use with the ? operator.

§Examples
use futures::stream::{self, TryStreamExt};

let mut stream = stream::iter(vec![Ok(()), Err(())]);

assert_eq!(stream.try_next().await, Ok(Some(())));
assert_eq!(stream.try_next().await, Err(()));
source

fn try_for_each<Fut, F>(self, f: F) -> TryForEach<Self, Fut, F>
where F: FnMut(Self::Ok) -> Fut, Fut: TryFuture<Ok = (), Error = Self::Error>, Self: Sized,

Attempts to run this stream to completion, executing the provided asynchronous closure for each element on the stream.

The provided closure will be called for each item this stream produces, yielding a future. That future will then be executed to completion before moving on to the next item.

The returned value is a Future where the Output type is Result<(), Self::Error>. If any of the intermediate futures or the stream returns an error, this future will return immediately with an error.

§Examples
use futures::future;
use futures::stream::{self, TryStreamExt};

let mut x = 0i32;

{
    let fut = stream::repeat(Ok(1)).try_for_each(|item| {
        x += item;
        future::ready(if x == 3 { Err(()) } else { Ok(()) })
    });
    assert_eq!(fut.await, Err(()));
}

assert_eq!(x, 3);
source

fn try_skip_while<Fut, F>(self, f: F) -> TrySkipWhile<Self, Fut, F>
where F: FnMut(&Self::Ok) -> Fut, Fut: TryFuture<Ok = bool, Error = Self::Error>, Self: Sized,

Skip elements on this stream while the provided asynchronous predicate resolves to true.

This function is similar to StreamExt::skip_while but exits early if an error occurs.

§Examples
use futures::future;
use futures::stream::{self, TryStreamExt};

let stream = stream::iter(vec![Ok::<i32, i32>(1), Ok(3), Ok(2)]);
let stream = stream.try_skip_while(|x| future::ready(Ok(*x < 3)));

let output: Result<Vec<i32>, i32> = stream.try_collect().await;
assert_eq!(output, Ok(vec![3, 2]));
source

fn try_take_while<Fut, F>(self, f: F) -> TryTakeWhile<Self, Fut, F>
where F: FnMut(&Self::Ok) -> Fut, Fut: TryFuture<Ok = bool, Error = Self::Error>, Self: Sized,

Take elements on this stream while the provided asynchronous predicate resolves to true.

This function is similar to StreamExt::take_while but exits early if an error occurs.

§Examples
use futures::future;
use futures::stream::{self, TryStreamExt};

let stream = stream::iter(vec![Ok::<i32, i32>(1), Ok(2), Ok(3), Ok(2)]);
let stream = stream.try_take_while(|x| future::ready(Ok(*x < 3)));

let output: Result<Vec<i32>, i32> = stream.try_collect().await;
assert_eq!(output, Ok(vec![1, 2]));
source

fn try_collect<C: Default + Extend<Self::Ok>>(self) -> TryCollect<Self, C>
where Self: Sized,

Attempt to transform a stream into a collection, returning a future representing the result of that computation.

This combinator will collect all successful results of this stream and collect them into the specified collection type. If an error happens then all collected elements will be dropped and the error will be returned.

The returned future will be resolved when the stream terminates.

§Examples
use futures::channel::mpsc;
use futures::stream::TryStreamExt;
use std::thread;

let (tx, rx) = mpsc::unbounded();

thread::spawn(move || {
    for i in 1..=5 {
        tx.unbounded_send(Ok(i)).unwrap();
    }
    tx.unbounded_send(Err(6)).unwrap();
});

let output: Result<Vec<i32>, i32> = rx.try_collect().await;
assert_eq!(output, Err(6));
source

fn try_filter<Fut, F>(self, f: F) -> TryFilter<Self, Fut, F>
where Fut: Future<Output = bool>, F: FnMut(&Self::Ok) -> Fut, Self: Sized,

Attempt to filter the values produced by this stream according to the provided asynchronous closure.

As values of this stream are made available, the provided predicate f will be run on them. If the predicate returns a Future which resolves to true, then the stream will yield the value, but if the predicate return a Future which resolves to false, then the value will be discarded and the next value will be produced.

All errors are passed through without filtering in this combinator.

Note that this function consumes the stream passed into it and returns a wrapped version of it, similar to the existing filter methods in the standard library.

§Examples
use futures::future;
use futures::stream::{self, StreamExt, TryStreamExt};

let stream = stream::iter(vec![Ok(1i32), Ok(2i32), Ok(3i32), Err("error")]);
let mut evens = stream.try_filter(|x| {
    future::ready(x % 2 == 0)
});

assert_eq!(evens.next().await, Some(Ok(2)));
assert_eq!(evens.next().await, Some(Err("error")));
source

fn try_filter_map<Fut, F, T>(self, f: F) -> TryFilterMap<Self, Fut, F>
where Fut: TryFuture<Ok = Option<T>, Error = Self::Error>, F: FnMut(Self::Ok) -> Fut, Self: Sized,

Attempt to filter the values produced by this stream while simultaneously mapping them to a different type according to the provided asynchronous closure.

As values of this stream are made available, the provided function will be run on them. If the future returned by the predicate f resolves to Some(item) then the stream will yield the value item, but if it resolves to [None] then the next value will be produced.

All errors are passed through without filtering in this combinator.

Note that this function consumes the stream passed into it and returns a wrapped version of it, similar to the existing filter_map methods in the standard library.

§Examples
use futures::stream::{self, StreamExt, TryStreamExt};
use futures::pin_mut;

let stream = stream::iter(vec![Ok(1i32), Ok(6i32), Err("error")]);
let halves = stream.try_filter_map(|x| async move {
    let ret = if x % 2 == 0 { Some(x / 2) } else { None };
    Ok(ret)
});

pin_mut!(halves);
assert_eq!(halves.next().await, Some(Ok(3)));
assert_eq!(halves.next().await, Some(Err("error")));
source

fn try_flatten(self) -> TryFlatten<Self>
where Self::Ok: TryStream, <Self::Ok as TryStream>::Error: From<Self::Error>, Self: Sized,

Flattens a stream of streams into just one continuous stream.

If this stream’s elements are themselves streams then this combinator will flatten out the entire stream to one long chain of elements. Any errors are passed through without looking at them, but otherwise each individual stream will get exhausted before moving on to the next.

§Examples
use futures::channel::mpsc;
use futures::stream::{StreamExt, TryStreamExt};
use std::thread;

let (tx1, rx1) = mpsc::unbounded();
let (tx2, rx2) = mpsc::unbounded();
let (tx3, rx3) = mpsc::unbounded();

thread::spawn(move || {
    tx1.unbounded_send(Ok(1)).unwrap();
});
thread::spawn(move || {
    tx2.unbounded_send(Ok(2)).unwrap();
    tx2.unbounded_send(Err(3)).unwrap();
    tx2.unbounded_send(Ok(4)).unwrap();
});
thread::spawn(move || {
    tx3.unbounded_send(Ok(rx1)).unwrap();
    tx3.unbounded_send(Ok(rx2)).unwrap();
    tx3.unbounded_send(Err(5)).unwrap();
});

let mut stream = rx3.try_flatten();
assert_eq!(stream.next().await, Some(Ok(1)));
assert_eq!(stream.next().await, Some(Ok(2)));
assert_eq!(stream.next().await, Some(Err(3)));
assert_eq!(stream.next().await, Some(Ok(4)));
assert_eq!(stream.next().await, Some(Err(5)));
assert_eq!(stream.next().await, None);
source

fn try_fold<T, Fut, F>(self, init: T, f: F) -> TryFold<Self, Fut, T, F>
where F: FnMut(T, Self::Ok) -> Fut, Fut: TryFuture<Ok = T, Error = Self::Error>, Self: Sized,

Attempt to execute an accumulating asynchronous computation over a stream, collecting all the values into one final result.

This combinator will accumulate all values returned by this stream according to the closure provided. The initial state is also provided to this method and then is returned again by each execution of the closure. Once the entire stream has been exhausted the returned future will resolve to this value.

This method is similar to fold, but will exit early if an error is encountered in either the stream or the provided closure.

§Examples
use futures::stream::{self, TryStreamExt};

let number_stream = stream::iter(vec![Ok::<i32, i32>(1), Ok(2)]);
let sum = number_stream.try_fold(0, |acc, x| async move { Ok(acc + x) });
assert_eq!(sum.await, Ok(3));

let number_stream_with_err = stream::iter(vec![Ok::<i32, i32>(1), Err(2), Ok(1)]);
let sum = number_stream_with_err.try_fold(0, |acc, x| async move { Ok(acc + x) });
assert_eq!(sum.await, Err(2));
source

fn try_concat(self) -> TryConcat<Self>
where Self: Sized, Self::Ok: Extend<<<Self as TryStream>::Ok as IntoIterator>::Item> + IntoIterator + Default,

Attempt to concatenate all items of a stream into a single extendable destination, returning a future representing the end result.

This combinator will extend the first item with the contents of all the subsequent successful results of the stream. If the stream is empty, the default value will be returned.

Works with all collections that implement the Extend trait.

This method is similar to concat, but will exit early if an error is encountered in the stream.

§Examples
use futures::channel::mpsc;
use futures::stream::TryStreamExt;
use std::thread;

let (tx, rx) = mpsc::unbounded::<Result<Vec<i32>, ()>>();

thread::spawn(move || {
    for i in (0..3).rev() {
        let n = i * 3;
        tx.unbounded_send(Ok(vec![n + 1, n + 2, n + 3])).unwrap();
    }
});

let result = rx.try_concat().await;

assert_eq!(result, Ok(vec![7, 8, 9, 4, 5, 6, 1, 2, 3]));
source

fn try_poll_next_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Option<Result<Self::Ok, Self::Error>>>
where Self: Unpin,

A convenience method for calling TryStream::try_poll_next on [Unpin] stream types.

source

fn try_all<Fut, F>(self, f: F) -> TryAll<Self, Fut, F>
where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future<Output = bool>,

Attempt to execute a predicate over an asynchronous stream and evaluate if all items satisfy the predicate. Exits early if an Err is encountered or if an Ok item is found that does not satisfy the predicate.

§Examples
use futures::stream::{self, StreamExt, TryStreamExt};
use std::convert::Infallible;

let number_stream = stream::iter(1..10).map(Ok::<_, Infallible>);
let positive = number_stream.try_all(|i| async move { i > 0 });
assert_eq!(positive.await, Ok(true));

let stream_with_errors = stream::iter([Ok(1), Err("err"), Ok(3)]);
let positive = stream_with_errors.try_all(|i| async move { i > 0 });
assert_eq!(positive.await, Err("err"));
source

fn try_any<Fut, F>(self, f: F) -> TryAny<Self, Fut, F>
where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future<Output = bool>,

Attempt to execute a predicate over an asynchronous stream and evaluate if any items satisfy the predicate. Exits early if an Err is encountered or if an Ok item is found that satisfies the predicate.

§Examples
use futures::stream::{self, StreamExt, TryStreamExt};
use std::convert::Infallible;

let number_stream = stream::iter(0..10).map(Ok::<_, Infallible>);
let contain_three = number_stream.try_any(|i| async move { i == 3 });
assert_eq!(contain_three.await, Ok(true));

let stream_with_errors = stream::iter([Ok(1), Err("err"), Ok(3)]);
let contain_three = stream_with_errors.try_any(|i| async move { i == 3 });
assert_eq!(contain_three.await, Err("err"));

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<S: ?Sized + TryStream> TryStreamExt for S