RxJS - map vs flatMap

Ben Lesh
InstructorBen Lesh
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 6 years ago

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.

[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.