flatMap, concatMap – In details

As promised in the previous chapter, now we will take a deeper dive into the flatMap and concatMap operators, as, by now, we have already gained some sort of expertise on the merge and concat operators and know the differences between them.

Let's start with the differences between flatMap and concatMap, after which, we will also discuss their ideal implementation scenarios. We will also discuss some of their variants to know them better.

In the previous chapter, we mentioned that flatMap internally uses the merge operator and concatMap internally uses the concat operator. However, what difference does that make? You just learned the differences between the merge and the concat operator, but what is the point of having two separate mapping operators based on them? So, let's start with an example. We will see an example with flatMap, and then we will try to implement the same with concatMap:

    fun main(args: Array<String>) { 
      Observable.range(1,10) 
        .flatMap { 
            val randDelay = Random().nextInt(10) 
            return@flatMap Observable.just(it) 
                         
.delay(randDelay.toLong(),TimeUnit.MILLISECONDS)//(1) } .blockingSubscribe { println("Received $it") } }

In the preceding program, we created an Observable instance. We then used the flatMap operator with the delay operator on it to add a random delay to the emissions.

The output is as follows:

From the output, we can see that the downstream didn't get the emissions in their prescribed order; I think you got the reason behind it, didn't you? That's right; the cause behind it is simply the merge operator, as the merge operator subscribes and reemits the emissions asynchronously all at one go, thus the order is not maintained.

Now, let's implement the code with the concatMap operator:

    fun main(args: Array<String>) { 
      Observable.range(1,10) 
         .concatMap { 
             val randDelay = Random().nextInt(10) 
             return@concatMap Observable.just(it) 
            .delay(randDelay.toLong(), TimeUnit.MILLISECONDS)//(1) 
          } 
         .blockingSubscribe { 
             println("Received $it") 
          } 
     } 

The output is as follows:

As the concatMap operator uses concat internally, it maintains the prescribed order of emissions.

So, when to use which operator? Let's take a look at the following real-time scenarios; all of them are applicable, especially when you are building an app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.12