Search code examples
flutterreactive-programmingreactivexrxdart

Flatten multiple streams, with events of only of the last stream


x is a stream. On each event, I generate a stream x_i that itself spawns events. From this set up, I want to generate a flattened output stream that contains only events of the most recent x_i, until x ends:

x:   ├─┬───┬─────┬────────┤
x_3:   │   │     └─E────H───I─...
x_2:   │   └─B───D────G───────...
x_1:   └─A─────C────F─────────...

The expected result is

     ├───A───B───D─E────H─┤

I can't use flatMap on x, because then all x_i events would be merged into the output stream, not just those of the most recent sub stream.

I also can't use concatMap because x_i are infinite, and the output stream would effectively be x_1.

This seems to me like a fairly common scenario, hence my question: Is this possible using standard RxDart (which I'm using), or do I need to implement this myself?


Solution

  • What you're looking for is swtichLatest operator of rxdart

    http://reactivex.io/documentation/operators/switch.html enter image description here