flatMap, mergeMap, switchMap and concatMap in rxjs?

后端 未结 6 474

Someone, please explain the difference between SwitchMap and FlatMap in terms of Javascript ( in angular perspective, rxjs 5)

In my understanding.

S

6条回答
  •  盖世英雄少女心
    2020-12-02 06:07

    Here is one more way of thinking about the difference between the different types of maps. This helped me get my head around it. I hope it might help others.

    Consider the following sources:

    • A source producing lower case letters from the alphabet: a,b,c & d
    • 4 separate "word" sources, each one producing 3 words starting with a particular letter from the alphabet - a,b,c or d - then completing

    To illustrate the difference between different kinds of maps, we will link items from the alphabet source to their "word" sources corresponding to that letter of the alphabet, using each different map to see the different outcomes.

    Map

    This is unlike the other maps because it does not introduce another source of observable. It just transforms an incoming value to another value.

    So output from the lower case source, going through a Map which transforms input to upper case, would just be:

    Input: a,b,c,d
    
    Output: A, B, C, D
    

    Switch Map

    This transforms each input into another source, switching output to come from that new source (ie subscribing to that new source). When another alpha input arrives, the "word" source changes (we unsubscribe from the previous "word" source).

    Input: a,b,c,d
    
    Output: animal, aardvark, bull, baker, beach, cow, dog, day, dinner
    

    Concat Map

    Like switchMap except that Concat waits until each source completes before moving on to the next.

    Input: a,b,c,d
    
    Output: animal, aardvark, axe, bull, baker, beach, cow, car, cat, dog, day, dinner
    

    Exhaust Map

    Like Concat Map except that it will ignore any inputs that come in while it is still completing the last source. The example below assumes that the alpha inputs "b" and "d" both came in while the previous mapped source was still completing, so they were ignored.

    Input: a,b,c,d
    
    Output: animal, aardvark, axe, cow, car, cat
    

    Merge Map (aka Flat Map)

    Like concatMap in that each source runs to completion, but a new source can start up while other sources are still going - so the sequences overlap.

    Input: a,b,c,d
    
    Output: animal, aardvark, bull, axe, baker, cow, car, beach, dog, day, cat, dinner
    

提交回复
热议问题