How can I return a filter or map from a function?

I feel like I must be missing something obvious but despite reading tons of docs I have not been able to get this to work. Here's what I'm trying to do:

pub async fn messages(&self) -> Map {
  self
    .pubsub // pubsub is type tokio::broadcast::Sender<SomeType>
    .subscribe()
    .into_stream()
    .filter(Result::is_ok)
    .map(Result::unwrap)
}

so that I then have a simple API to call elsewhere:

let stream = foo
  .messages()
  .map(|data| match data {
    // process the messages
  })

Box.pin(stream)

This code works when it's called directly (foo.pubsub.subscribe().into_stream().map() etc) but how can I get the return type correct so that I can move this into a method? What am I missing?

You want the impl Trait syntax.

pub async fn messages(&self) -> impl Stream<Item = SomeType> {
  self
    .pubsub
    .subscribe()
    .into_stream()
    .filter(Result::is_ok)
    .map(Result::unwrap)
}
1 Like

Thanks @alice! For anyone else that stumbles onto this and still gets an error for expected opaque type, found X it's because I had an extraneous async in this example. messages doesn't need to be async here.

Good point!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.