What is the difference between flatmap and switchmap in RxJava?

后端 未结 7 1754
忘掉有多难
忘掉有多难 2020-11-29 15:07

The rxjava doc definition of switchmap is rather vague and it links to the same page as flatmap. What is the difference between the two operators?

相关标签:
7条回答
  • 2020-11-29 16:11

    Map, FlatMap, ConcatMap and SwitchMap applies a function or modifies the data emitted by an Observable.

    • Map modifies each item emitted by a source Observable and emits the modified item.

    • FlatMap, SwitchMap and ConcatMap also applies a function on each emitted item but instead of returning the modified item, it returns the Observable itself which can emit data again.

    • FlatMap and ConcatMap work is pretty much same. They merge items emitted by multiple Observables and returns a single Observable.

    • The difference between FlatMap and ConcatMap is the order in which the items are emitted.
    • FlatMap can interleave items while emitting i.e the emitted items order is not maintained.
    • ConcatMap preserves the order of items. But the main disadvantage of ConcatMap is, it has to wait for each Observable to complete its work thus asynchronous is not maintained.
    • SwitchMap is a bit different from FlatMap and ConcatMap. SwitchMap unsubscribes from the previous source Observable whenever new item started emitting, thus always emitting the items from current Observable.
    0 讨论(0)
提交回复
热议问题