Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    RxJS - map vs flatMap

    Ben LeshBen Lesh

    What is the difference between map and flatMap? How do you take an Observable of Observables and output a single stream? This lesson is a quick look at map and flatMap and how they relate.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    What's the difference between map and flatmap? First, let's show what map is. To show that, I need a source stream, so I'm going to make an interval. It takes a tenth of a second, and I'm only going to take 10 values, and subscribe to it, be sure that it's working. Let's write it out to console.

    You'll see that what I get is the numbers zero through nine, and then they tick in at every tenth of a second. What map does is map enables me to map, just like you would with an array map, the value to a new value. So, I could take it and I could multiply it by two.

    Run. Let's see, now I have multiples of two coming in. It took zero, multiply it by zero, you got zero. One, multiplied by two is two, and so on.

    But what happens if I want to do something asynchronous in here? To show this, I'm going to return an observable timer, which is just going to wait for half of a second, and then map to exactly the same values.

    This is going to basically just delay for half a second, and then return exactly the same value I pumped in. I am returning an observable from my map. This doesn't get crazy over here because of how JS Bin handles objects, I'm going to two string this. Let's run it. You're going to see I get objects back.

    That's because these objects are observables. I'd really, really like to get my values back into my stream. There's actually two ways to do this. From here, I can do a "merge all." What a merge all does is, it takes in a stream of observables, or an observable of observables, and merges them together as they come in.

    It subscribes to each one, and pumps them into one output stream. Now, when I run this, you'll see I get my zero through nine yet again. But there's a more concise way to do exactly the same thing. Instead of merge all, I can use flatmap. What flatmap is going to do is it's going to perform this mapping function and then subscribe to each observable returned by the map.