It seems that these 2 functions are pretty similar. They have same signature (accepting rx.functions.Func1<? super T, ? extends Observable<? extends R>> func
), and their marble diagrams look exactly same. Can't paste the pics here, but here's one for concatMap, and here's one for flatMap. There seems to be some subtle difference in the description of resulting Observable
, where one produced by concatMap
contains items that result from concatinating resulting Observables, and the one produced by flatMap
contains items that result from first merging the resulting Observables, and emitting the result of that merger.
However, this subtlety is totally unclear to me. Can anyone give a better explanation of this difference, and ideally give some examples illustrating this difference.
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.
A map operator transforms each of the values from the Observable sequence. A flatmap operator is used to transform an observable by breaking it into smaller observables containing individual values from the first observable.
Only concatMap will make sure that our list stays the same. Because of synchronous calls in the concatMap, increase of the processing time must be taken into account. Sending some information for each item in list (eg. sending 'like' message for each post in the list).
To use concatMap in Angular first we need to import it our Component or Service. import { concatMap } from 'rxjs/operators'; In the following code, we have two observables srcObservable which emits 1,2,3,4 & innerObservable which emits 'A','B','C','D' . The ConcatMap receives its values from the srcObservable .
As you wrote, the two functions are very similar and the subtle difference is how the output is created ( after the mapping function is applied).
Flat map uses merge operator while concatMap uses concat operator.
As you see the concatMap output sequence is ordered - all of the items emitted by the first Observable being emitted before any of the items emitted by the second Observable,
while flatMap output sequence is merged - the items emitted by the merged Observable may appear in any order, regardless of which source Observable they came from.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With