Sobes.tech
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:

  1. "ax", "bx", "cx", "dx"
  2. "dx", "cx", "bx", "ax"
  3. "bx", "cx", "ax", "dx" Answer: second option.

switchMap – answer options:

  1. "ax", "bx", "cx", "dx"
  2. "dx", "cx", "bx", "ax"
  3. "dx" Answer: third option.

concatMap – answer options:

  1. "dx"
  2. "dx", "cx", "bx", "ax"
  3. "ax", "bx", "cx", "dx" Answer: third option.