Returning futures::stream::Then from a function

I'm trying to write a function that takes a &self (of the struct it's for) and returns a futures::stream::Then. I've omitted the type parameters of Then - any working example here would help me understand what's going on.

A preliminary question - is this a reasonable thing to return?/is there a better return type? I haven't been able to find any questions/examples online about returning the stream wrapper types, so maybe I'm just trying to do something really unusual. I need this function to do some async processing on a list of items, so I'm converting the list to a stream, passing in an async closure, and returning the Then result. I want to call this function on several different inputs, then merge all the streams.

Assuming that's do I write the function signature? I've tried variations of:

  • impl Stream. But the compiler gives me a lifetime error, where the &self parameter is required to be static. As far as I can tell, this is because the stream could be run at any time (because it's async), so self would also need to live that long? Is there a way to tell the compiler that I will await this stream to completion before self dies?
  • Then<...>. But for the life of me I cannot get the compiler to be happy with the third generic type parameter, which is the type of the closure.

Will something like this work?

fn then<'a>(&'a self, ...) -> impl Stream + 'a

This way, you'll explicitly tie the Stream's lifetime to the self's one. If I understand correctly, by default it is the following:

fn then(&'_ self, ...) -> impl Stream + 'static

i.e. self has some elided lifetime, but impl Trait without any further restrictions is 'static.


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.