Skip to content

Transformation Operators : FlatMap

Devrath edited this page Dec 29, 2023 · 2 revisions
Screenshot 2023-12-29 at 5 54 26β€―PM

What is the FlatMap operator ?

  • A FlatMap operator helps us to transform the input of an observable to another observable, Then flattens it and sends as a result downstream.
  • Imagine there are 6 emissions in the observable we are observing, Now when we apply a FlatMap operation we can transform each emission into 6 observables, Perform some operation on the observable, and then return as observable finally the results will be flattened into a list of final emissions to downstream

Code

    private val flatMapObservable = Observable.just("USA","RUSSIA","AUSTRALIA")

    fun demoFlatMap() {

        flatMapObservable
            .flatMap{ input ->
                /**
                 * 1) Here we shall receive the string one by one
                 * 2) Pass it into a new observable
                 * 3) Get the result from the observable
                 */
                // <----------- Observable ----------->
                performFlatMapLongOperation(input)
            }
            .subscribe{
                // Finally the result of all the observables are flattened into a string on new emission
                println("Received-> $it")
            }

    }

    private fun performFlatMapLongOperation(input : String) : Observable<String> {

        return Observable.create {

            // Perform some operation (Let us assume long running operation)
            it.onNext("$input - observable")

            // Complete the current observable
            it.onComplete()
        }

    }

Output

Received-> USA - observable
Received-> RUSSIA - observable
Received-> AUSTRALIA - observable
Clone this wiki locally