Rust futures `try_filter_map` causing panic: 'async fn resumed after completion'

Viewed 330

I have a Stream that generates Result's, I want to apply a try_filter_map() on these items and take the first item that does not result in an error.

Consider the following example: (Playground)

use futures::{pin_mut, prelude::*};
use tokio;

#[tokio::main]
async fn main() {
    let s = stream::iter(vec![Ok(1), Ok(2), Ok(3)])
        .try_filter_map(|v| async move { if v == 1 { Err("Ohno!") } else { Ok(Some(v)) } })
        .inspect_err(|err| println!("Error {:?}", err))
        .filter_map(|r| future::ready(r.ok()));
    pin_mut!(s);
    let result = s.next().await;
    println!("{:?}", result);
}

When I run this code I receive the following error:

Error "Ohno!"
thread 'main' panicked at '`async fn` resumed after completion'

I am fairly new to Rust and could use some help to solve this issue.

1 Answers

It seems like this is a bug. Until a new release fixes the issue, it looks like you are using try_filter_map without actually filtering the stream? If that is the case, you can use and_then instead:

let s = stream::iter(vec![Ok(1), Ok(2), Ok(3)])
  .and_then(|v| future::ready(if v == 1 { Err("Ohno!") } else { Ok(v) }))
  .inspect_err(|err| println!("Error {:?}", err))
  .filter_map(|r| future::ready(r.ok()));
Related