skip to content

In RxJava 3, a search box debounces typing and calls an API per query: why use switchMap rather than flatMap or concatMap?

level: middleimportance: must knowfreq 62%

answer

  1. only the latest query matters
  2. what happens to the older request
  3. merge, queue, or replace
  4. the previous inner gets disposed
  5. recover inside the inner

basics

~20 s

switchMap disposes the previous request as soon as a newer query arrives, so only the latest query's results reach the screen. flatMap runs every request at once and can show stale results out of order; concatMap queues them and lags behind the typing.

solid answer

~40 s

All three map each query to an inner stream; they differ in what happens to the previous one. `flatMap` subscribes to every inner at once and merges the results, so a slow reply for "an" can land after the reply for "android" and overwrite it. `concatMap` runs one inner at a time, in order, so fast typing builds a queue of obsolete requests. `switchMap`, or `switchMapSingle` for an API that returns a `Single`, disposes the previous inner when a new query arrives, which also cancels the in-flight call when the source supports cancellation on disposal. Put `debounce(300, TimeUnit.MILLISECONDS)` and `distinctUntilChanged()` in front of it, and recover inside the inner with `onErrorReturn`: an error that escapes the inner terminates the whole chain, and the search box stops responding.

code

kotlin · 51 lines
kotlin
import androidx.lifecycle.ViewModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.PublishSubject
import java.util.concurrent.TimeUnit

interface SearchApi {
    fun search(query: String): Single<List<String>>
}

sealed interface SearchState {
    data class Results(val items: List<String>) : SearchState
    data class Failed(val message: String) : SearchState
}

class SearchViewModel(private val api: SearchApi) : ViewModel() {
    private val queries = PublishSubject.create<String>()
    private val disposables = CompositeDisposable()

    init {
        disposables.add(
            queries
                .map { it.trim() }
                .debounce(300, TimeUnit.MILLISECONDS)  // emits on computation()
                .distinctUntilChanged()
                .switchMapSingle { query ->
                    api.search(query)
                        .subscribeOn(Schedulers.io())
                        .map<SearchState> { items -> SearchState.Results(items) }
                        .onErrorReturn { e -> SearchState.Failed(e.message ?: "search failed") }
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    { state -> render(state) },
                    { e -> render(SearchState.Failed(e.toString())) },
                ),
        )
    }

    fun onQueryChanged(text: String) {
        queries.onNext(text)
    }

    override fun onCleared() {
        disposables.clear()
    }

    private fun render(state: SearchState) { /* push to UI state */ }
}

go deeper

for a junior

Know that switchMap keeps only the latest request running, and that debounce waits for typing to pause before passing a query on.

for a middle

Compare flatMap, concatMap and switchMap by concurrency, ordering and fate of the previous inner, and place debounce and distinctUntilChanged correctly.

for a senior

Keep the pipeline alive in production: recover inside the inner, know what disposal really cancels, and expect late errors from interrupted blocking calls.

for a principal

Judge how such pipelines are tested with a TestScheduler and whether a self-contained screen like search is a good first candidate for moving to Flow.

## The scenario A screen has a search box. Each keystroke pushes the current text into a stream, and for each query the app calls a search API that returns a `Single<List<Result>>`. The codebase is being moved to Kotlin's `Flow` one screen at a time, but this screen still runs on RxJava 3. The questions an interviewer probes are: which operator turns queries into requests, how fast typing is tamed, and what keeps the pipeline alive when a request fails. ## Three ways to flatten Each of the three operators takes an upstream item, maps it to an **inner** source and flattens the inners' results into one stream. The difference is what happens when a new upstream item arrives while an earlier inner is still running. | Operator | Concurrency | Output order | Previous inner when a new item arrives | Fits | |---|---|---|---|---| | `flatMap` | all inners at once | interleaved, by arrival | keeps running | independent work: upload every photo | | `concatMap` | one inner at a time | strictly upstream order | finishes first; new item waits | ordered work: apply edits in sequence | | `switchMap` | only the latest inner | latest only | **disposed** | "only the newest request matters": search, autocomplete | Each has typed variants that take a `Single`, `Maybe` or `Completable` mapper, such as `flatMapSingle`, `concatMapSingle` and `switchMapSingle`. ## Why switchMap fits search - **No stale results.** With `flatMap`, the reply for "an" may arrive after the reply for "android" and overwrite the newer results. `switchMap` disposes the "an" request the moment "android" arrives, so its late reply is never emitted. - **Less wasted work.** Disposing the inner propagates up to its source. A source built to cancel on disposal, such as a call made through Retrofit's RxJava adapter, stops the HTTP request. A blocking call inside `Single.fromCallable` cannot be undone; disposal interrupts its `io()` thread, and an error it throws afterwards is routed to `RxJavaPlugins.onError` as an undeliverable error. - **No backlog.** `concatMap` would run every intermediate query in turn, so the screen lags further behind the faster the user types. ## Shaping the input The operators in front of `switchMap` decide how many requests are made at all: - `debounce(300, TimeUnit.MILLISECONDS)` waits until no new text has arrived for 300 ms and then emits the last value: one request per pause in typing. Without an explicit `Scheduler` it emits on `Schedulers.computation()`. - `throttleFirst(window, unit)` emits the first item and ignores the rest for the window, which suits button taps, not typing. - `throttleLatest(timeout, unit)` emits at most once per timeout during a burst, for progress-style updates. - `distinctUntilChanged()` skips a query equal to the previous one, such as typing a letter and deleting it again. - `map { it.trim() }` and `filter { it.length >= 2 }` drop queries not worth sending. ## Keeping the stream alive after an error An error from the active inner propagates downstream and terminates the whole chain, including the subscription to the text stream. After one failed request, the search box silently stops searching. Three fixes, in order of preference: 1. **Recover inside the inner.** Put `onErrorReturn { ... }` or `onErrorResumeNext { ... }` on the request itself, turning a failure into a value such as an error state. The outer chain never sees an error. 2. **Model results as state.** Map success to a "results" state and failure to a "failed" state of one sealed type, so the subscriber renders both. 3. **retry() on the outer chain.** It resubscribes to the whole upstream after an error. That works with a subject as the source, but keystrokes during the gap are lost and the failure is hidden from the user. Also place `observeOn(AndroidSchedulers.mainThread())` after `switchMap` and before rendering, because `debounce` and the request both run on background threads. ## When flatMap and concatMap are right - `flatMap` when every item's work must finish and order does not matter, and consider its `maxConcurrency` overload to cap parallel requests. - `concatMap` when order matters and each step must see the previous one's effect. - `switchMap` whenever a newer item makes the older one's result worthless.

  • The search stops reacting after one failed request. What happened, and how do you fix it?
    The request's error escaped `switchMap`, so the whole chain terminated with `onError` and the subscription to the query stream ended. Recover inside the inner, with `onErrorReturn` or `onErrorResumeNext` on the request, so a failure becomes a value and the outer chain keeps running. `retry()` on the outer chain also restores it, but resubscribes to the whole upstream and hides the failure.
  • When is debounce the wrong choice and throttleFirst the right one?
    `debounce` waits for a quiet period and then emits the last item, which suits typing. `throttleFirst` emits the first item at once and ignores the rest for a window, which suits a button where the first tap should act immediately and double taps should be dropped.
  • Does switchMap guarantee that the old HTTP request stops?
    It guarantees that the old inner is disposed and its result is never emitted. Whether the work stops depends on the source: one wired to cancel on disposal, such as a call made through Retrofit's RxJava adapter, stops the request. A blocking call inside `Single.fromCallable` keeps running until its interrupted thread gives up, and an error it throws then goes to `RxJavaPlugins.onError`.

Ordering at a counter and changing your mind: switchMap tells the cook to bin the first order, flatMap lets the cook make both and serve whichever is ready last, and concatMap makes you wait for the first dish before the second is started.

  • flatMap keeps results in the order the queries were typed.
  • concatMap cancels the previous request when a new query arrives.
  • switchMap waits for the current request to finish before starting the next one.
  • An error inside one request is harmless; the query stream keeps running.
  • debounce emits the first keystroke immediately, then ignores the rest for the window.