Someone, please explain the difference between SwitchMap and FlatMap in terms of Javascript ( in angular perspective, rxjs 5)
In my understanding.
SwitchMap only emits the latest observable value and cancel previous observable.
flatMap collects all individual observable and returns all observables in a single array without caring the order of observable. works asynchronously.
concatMap preserve the order and emits all observable value, works synchronously
is that right?
how does mergeMap works differently from above?
someone, please explain with an example.
Taking this from a previous answer:
Here is an example of how each of the operators behaves when the source is immediate items (0,1,2,3,4) and the map function creates an Observable that delays each item by 500ms:
const { mergeMap, flatMap, concatMap, switchMap, exhaustMap } = Rx.operators;
const example = operator => () =>
Rx.Observable.from([0,1,2,3,4])
.pipe(
operator(x => Rx.Observable.of(x).delay(500))
)
.subscribe(console.log, () => {}, () => console.log(`${operator.name} completed`));
const mm = example(mergeMap);
const fm = example(flatMap);
const cm = example(concatMap);
const sm = example(switchMap);
const em = example(exhaustMap);
.examples > div {
cursor: pointer;
background-color: #4CAF50;
color: white;
padding: 7px 16px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.8/Rx.js"></script>
<div class='examples'>
<div onClick='mm()'>mergeMap </div>
<div onClick='fm()'>flatMap</div>
<div onClick='cm()'>concatMap</div>
<div onClick='sm()'>switchMap</div>
<div onClick='em()'>exhaustMap</div>
</div>