Search code examples
rxjsnestedswitchmap

Why are these two observables emitting different streams?


I am using marble diagrams to show the output of two different observables. The first uses a switchmap, that pipes into another switchmap. The second observable has two switchmaps in the same pipe.

Here are the two marble flows:

The first uses switchmaps inside inner piping https://rxviz.com/v/38MavX78

The second uses switchmaps inside a single pipe https://rxviz.com/v/9J9zNpq8

How come they have different outcome?


Solution

  • My understanding is that switchMap does what it sounds like from the name - it switches the Observable chain from one Observable (the "outer" one) to another (the "inner" one). If the outer Observable emits before the inner one completes, then switchMap will unsubscribe from that inner Observable, and re-subscribe, effectively "cancelling" the first subscription. Docs here.

    Now in your first case, you have nested the switchMap to grandchildren$ INSIDE the switchmap to children$. Therefore when parent$ emits the second time, it will cancel the switch to children$ AND the switch to grandchildren$, since grandchildren$ is a part of children$ (nested within it).

    However, in the second case, you do not have them nested. Therefore when parent$ emits the second time it will indeed cancel the children$ subscription, but children$ will not emit anything when that happens, leaving the chain further down untouched. Therefore grandchildren$ keeps emitting until children$ actually emits something, which will be 1000ms after it was re-subscribed to when parent$ emitted.

    Hopefully that makes sense.