-
Notifications
You must be signed in to change notification settings - Fork 0
Transformation Operators : FlatMap
Devrath edited this page Dec 29, 2023
·
2 revisions
- 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
FlatMapoperation 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
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()
}
}Received-> USA - observable
Received-> RUSSIA - observable
Received-> AUSTRALIA - observable