Junior — Senior
Comparison of flatMap, switchMap, and concatMap behavior in RxJava
livecode
Task condition
Determine what output order will be obtained when replacing (method) with each of the operators — flatMap, switchMap, and concatMap, using the code below.
val items = mutableListOf("a", "b", "c", "d")
val counter = AtomicInteger(4)
Observable.fromIterable(items). (method) { item ->
val delay = counter.decrementAndGet() * 10
Observable.just(item + "x").delay(delay.toLong(), TimeUnit.SECONDS)
}
.doOnNext { println(it) }
.subscribe()
flatMap – answer options:
- "ax", "bx", "cx", "dx"
- "dx", "cx", "bx", "ax"
- "bx", "cx", "ax", "dx" Answer: second option.
switchMap – answer options:
- "ax", "bx", "cx", "dx"
- "dx", "cx", "bx", "ax"
- "dx" Answer: third option.
concatMap – answer options:
- "dx"
- "dx", "cx", "bx", "ax"
- "ax", "bx", "cx", "dx" Answer: third option.