The flatMap operator

Where the map operator takes each emission and transforms them, the flatMap operator creates a new producer, applying the function you passed to each emission of the source producer.

So, let's look at this example:

    fun main(args: Array<String>) { 
      val observable = listOf(10,9,8,7,6,5,4,3,2,1).toObservable() 
      observable.flatMap { 
        number-> Observable.just("Transforming Int to String $number") 
      }.subscribe { 
        item-> println("Received $item") 
      } 
   } 

Here is the output:

The output is similar to the previous one, but the logic is different. Instead of just returning the String, we are returning Observable with the desired String. Although, for this example, you seem to have no benefit using it, think of a situation when you need to derive multiple items from a single emission. Consider the following example where we will create multiple items from each emission:

    fun main(args: Array<String>) { 
      val observable = listOf(10,9,8,7,6,5,4,3,2,1).toObservable() 
      observable.flatMap { 
        number-> 
        Observable.create<String> {//(1) 
          it.onNext("The Number $number") 
          it.onNext("number/2 ${number/2}") 
          it.onNext("number%2 ${number%2}") 
          it.onComplete()//(2) 
        } 
      }.subscribeBy ( 
         onNext = { 
            item-> println("Received $item") 
         }, 
         onComplete = { 
            println("Complete") 
         } 
       ) 
    }   

Let's take a look at the output, and then we will try to understand the program:

In this program, we've created a new instance of Observable inside the flatMap operator, which will emit three strings. On comment (1), we created the Observable instance with the Observable.create operator. We will emit three strings from the Observable.create operator, and, on comment (2), we will send an onComplete notification after emitting three items from Observable.

However, take a look at the output; it emitted all the items before sending the onComplete notification. The reason is that all Obervables are combined together and then subscribed to the downstream. The flatMap operator internally uses the merge operator to combine multiple Observables.

The concatMap performs the same operation using the concat operator instead of the merge operator to combine two Observable/Flowables.

We will learn more about these operators (merge, concat, and other combining operators) in the next chapter.

We will again take a look at flatMap, along with concatMap, switchMap, and flatMapIterable in Chapter 6More on Operators and Error Handling after gaining some knowledge on merging and concatenating producers.

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

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