Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    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.

    rxjsRxJS
    Code

    Code

    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
    Transcript

    Transcript

    00:01 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.

    00:25 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.

    00:48 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.

    00:57 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.

    01:14 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.

    01:36 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.

    02:01 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.

    Discuss

    Discuss