このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

switchLatest, flattenMerge & friends

A stream of streams, flattened: keep the newest, run them all, play them in order, or ignore the extra — and start later sources immediately with concatEager.

FxEvents<T> FxEvents<Stream<T>>.switchLatest() FxEvents<T> FxEvents<Stream<T>>.flattenMerge({int? concurrent}) FxEvents<T> FxEvents<Stream<T>>.flattenConcat() FxEvents<T> FxEvents<Stream<T>>.exhaustLatest() FxEvents<T> concatEager<T>(Iterable<Stream<T>> sources)

Lecture

Sometimes the events already are inner streams — a socket per session, a request already built. There is no mapper to write; the only question is the flattening policy. That is what these identity forms are: switchLatest is switchMap((s) => s), flattenMerge is mergeMap, flattenConcat is concatMap, exhaustLatest is exhaustMap. An FxEvents of FxEvents flattens as .map((e) => e.stream).switchLatest().

switchLatest mirrors only the newest inner stream: a fresh one cancels the previous mid-flight. Use it when older inners become worthless — the current tab's feed, the current query's results. The chain closes when the outer has closed and the last inner completes.

The other three are the rest of the policy table. flattenMerge runs every inner at once (cap with concurrent: n); flattenConcat plays each to completion before the next begins; exhaustLatest keeps the first and ignores inners that arrive while one is still running.

concatEager is the sibling of FxEvents.concat. Both emit in source order, but concat waits to subscribe to the next source until the current one completes — a cold later source has not even started. concatEager subscribes to every source immediately and buffers later events until their turn. That is how you start a request now and still play the responses in order. fxdart events layer, after Rx's switchAll, mergeAll, concatAll, exhaustAll and concatEager.

Demo 1 · switchLatest — newest inner wins

Demo 2 · flattenConcat vs switchLatest

Try it yourself

Exercise: concatEager vs concat — later starts immediately.

Related: switchMap — the mapped form of switchLatest · mergeMap — mergeMap, concatMap, exhaustMap · FxEvents.concat — subscribe-later sibling of concatEager