skip to content

Reactive & Concurrency

Non-blocking and concurrent programming through libraries rather than raw threads: reactive streams on the JVM, effect systems in Scala, and async runtimes in Rust. Interviewers ask because backpressure and structured concurrency are what separate these from simply 'making it async'.

on this pageshow

explore

questions

6

In RxJava 3, when do you return a Single, Maybe or Completable instead of an Observable, and what does subscribe() give back?

level: juniorimportance: must knowfreq 72%

answer

  1. count the signals each type carries
  2. one value, maybe one, or none
  3. lambda subscribe hands back a handle
  4. Disposable collected in a CompositeDisposable
  5. always pass an onError

basics

~20 s

Choose by how many items the operation yields: Single for exactly one or an error, Maybe for zero or one, Completable for none, Observable for a stream. Lambda subscribe() calls return a Disposable to dispose when the owner goes away.

solid answer

~40 s

RxJava 3 has five base types, chosen by the shape of the result. A network fetch that returns one body is a `Single` (`onSuccess` or `onError`); a cache lookup that may find nothing is a `Maybe` (`onSuccess`, an empty `onComplete`, or `onError`); a write with no result is a `Completable` (`onComplete` or `onError`); a stream of many values, such as text changes, is an `Observable`, or a `Flowable` when the producer can outrun the consumer. The lambda forms of `subscribe(...)` return a `Disposable`: calling `dispose()` stops the upstream work and detaches your callbacks from the source. On Android you collect them in a `CompositeDisposable` and call `clear()` in `onCleared()` or `onDestroy()`, and you always pass an `onError` lambda, because a missing one turns any error into an `OnErrorNotImplementedException` that crashes the app.

code

kotlin · 38 lines
kotlin
import androidx.lifecycle.ViewModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers

data class Profile(val id: String, val name: String)

interface ProfileRepository {
    fun fetchProfile(id: String): Single<Profile>   // exactly one value or an error
    fun cachedProfile(id: String): Maybe<Profile>   // a value, or nothing
    fun saveProfile(profile: Profile): Completable  // no value: done or failed
}

class ProfileViewModel(private val repo: ProfileRepository) : ViewModel() {
    private val disposables = CompositeDisposable()

    fun load(id: String) {
        disposables.add(
            repo.fetchProfile(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    { profile -> show(profile) },
                    { error -> showError(error) },
                ),
        )
    }

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

    private fun show(profile: Profile) { /* update UI state */ }
    private fun showError(error: Throwable) { /* update UI state */ }
}

go deeper

for a junior

Know which of the five base types fits one value, an optional value, no value or many values, and that the lambda subscribe() returns a Disposable you must dispose.

for a middle

Explain what each type's observer receives, why onError is mandatory, and how CompositeDisposable.clear() differs from dispose() in a ViewModel or fragment.

for a senior

Show where forgotten disposals really leak, such as endless sources holding callbacks that capture views, and how you would catch them in review or with a leak detector.

for a principal

Set house rules for the codebase: repositories return the narrowest type, every subscribe carries onError, and disposal lives in one lifecycle-bound place.

## The five base types RxJava 3 (package `io.reactivex.rxjava3.core`) gives every asynchronous operation one of five **base types**. They differ in how many items they may emit and which terminal signals their observer receives. | Type | Emits | Observer receives | Typical Android use | |---|---|---|---| | `Observable` | 0..N items, no backpressure | `onNext`, then `onComplete` or `onError` | text changes, clicks, short streams | | `Flowable` | 0..N items, with backpressure | same, plus `request(n)` | large or fast producers, database rows | | `Single` | exactly 1 item or an error | `onSuccess` or `onError` | one HTTP call, one computed value | | `Maybe` | 0 or 1 item, or an error | `onSuccess`, `onComplete` or `onError` | a cache lookup that may miss | | `Completable` | no items | `onComplete` or `onError` | a save, a delete, a sync trigger | The narrower types exist because the signature is documentation. A repository method returning `Single<User>` promises one user or a failure; returning `Observable<User>` makes every caller wonder whether more users, or no user at all, might arrive. ## Why the narrow types pay off - **Intent in the signature.** `Completable saveProfile(...)` cannot be misread as returning data, and a reviewer sees immediately that `Maybe` callers must handle the empty case. - **No fake completion handling.** A `Single` observer has no `onComplete` to forget; a `Maybe` forces you to decide what "not found" means. - **Typed operators.** `flatMapSingle`, `flatMapMaybe`, `flatMapCompletable`, `concatMapSingle` and `switchMapSingle` compose the narrow types into streams without converting them first. - **Explicit conversions.** `toObservable()`, `toMaybe()`, `ignoreElement()`, `firstOrError()` and `singleElement()` move between types when a caller really needs another shape. ## What subscribe() returns The **lambda overloads** of `subscribe` (`subscribe(onNext)`, `subscribe(onNext, onError)`, `subscribe(onNext, onError, onComplete)` and their `Single`, `Maybe` and `Completable` equivalents) return a `Disposable`. That handle has two methods that matter: - `dispose()` cancels the subscription: upstream operators stop, scheduled work is cancelled, and the source lets go of the observer, so it no longer keeps your callbacks reachable. - `isDisposed()` tells you whether that has happened. The overload that takes a full `Observer` (`subscribe(observer)`) returns nothing; the observer receives its `Disposable` in `onSubscribe`. When you want the observer back as a handle, `subscribeWith(observer)` returns it. Since **3.1.0**, there is also an overload that takes a `DisposableContainer`, such as a `CompositeDisposable`: it adds the subscription to the container and removes it again once the sequence terminates or is disposed. ## The leak a forgotten Disposable causes A subscription keeps its callbacks reachable until it terminates or is disposed. The callbacks usually capture a view, a fragment or a ViewModel, so: 1. A one-shot `Single` that outlives its screen keeps that screen in memory until the call returns, and then runs UI code against a dead view. 2. An endless source (`Observable.interval`, a subject, a stream of text changes) never terminates, so the screen it captured is never freed. 3. Each time the screen is recreated, a new subscription is added on top of the old ones, and work multiplies. The house pattern is one `CompositeDisposable` per owner: `add()` every subscription and call `clear()` when the owner ends, in `ViewModel.onCleared()` or `onDestroy()`. The difference between the two release methods matters: - `clear()` disposes everything held and leaves the container usable for later `add()` calls. - `dispose()` disposes everything and marks the container itself disposed: any later `add()` disposes the new `Disposable` immediately and returns `false`. A fragment that calls `dispose()` in `onDestroyView` and subscribes again in `onViewCreated` silently receives nothing. ## Errors you must not leave unhandled RxJava never swallows an error. If you call `subscribe(onNext)` with no `onError` and the source fails, RxJava wraps the error in `OnErrorNotImplementedException` and passes it to `RxJavaPlugins.onError`. With no global handler installed, that prints the stack trace and calls the current thread's uncaught exception handler, which on Android terminates the app. Always pass an `onError`, even if it only logs and shows a message. RxJava 3 also rejects `null` as a value, as RxJava 2 did: a `map` lambda that returns `null` fails the stream with a `NullPointerException` ("The mapper function returned a null value."). Absence is modelled with `Maybe`, an `Optional`, or a sealed result type. ## Summary - Pick the base type by how many items the operation produces. - Keep the `Disposable` from every lambda `subscribe`, add it to a `CompositeDisposable`, and `clear()` it when the owner ends. - Never subscribe without an `onError`.

  • What is the difference between CompositeDisposable.clear() and CompositeDisposable.dispose()?
    Both dispose every `Disposable` currently held. `clear()` leaves the container usable, so later `add()` calls work normally. `dispose()` marks the container itself disposed, and any `Disposable` added afterwards is disposed immediately while `add()` returns `false`. A fragment that disposes in `onDestroyView` and subscribes again in `onViewCreated` therefore gets no updates; use `clear()` for a container that outlives one view.
  • What happens if you subscribe to a Single with only an onSuccess lambda and the call fails?
    The error has nowhere to go, so RxJava wraps it in `OnErrorNotImplementedException` and routes it to `RxJavaPlugins.onError`. Without a custom handler that prints the stack trace and calls the thread's uncaught exception handler, which on Android terminates the app. Pass an `onError` lambda on every subscribe, even one that only logs.
  • Why does a map lambda that returns null break an RxJava 3 stream?
    RxJava 2 and 3 refuse `null` as a value. `map` checks its result and fails the stream with a `NullPointerException` whose message is "The mapper function returned a null value." Model a missing value with `Maybe`, an `Optional`, or a sealed result type instead.

  • A Single is just an Observable that emits once; the type adds nothing.
  • subscribe() returns the stream itself, so you can keep chaining operators.
  • Disposables from one-shot network calls never need disposing because they finish anyway.
  • Leaving out the onError lambda just means errors are silently ignored.
  • Calling CompositeDisposable.dispose() in onDestroyView lets the fragment reuse it later.

Assumes RxJava 3.1.x; the subscribe overload that takes a DisposableContainer was added in 3.1.0.

open as a page

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%

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.

open as a page

In RxJava 3, what is the difference between subscribeOn and observeOn, and what happens when a chain uses each of them twice?

level: middleimportance: must knowfreq 75%

basics

~20 s

subscribeOn picks the Scheduler on which subscription, and so a cold source's work, starts; with several, the one nearest the source wins. observeOn switches the thread for everything below it, and each extra observeOn adds another hop.

open as a page

An RxJava 3 Flowable chain fails with MissingBackpressureException: what does that mean, and how do you choose a backpressure strategy?

level: seniorimportance: should knowfreq 28%

basics

~20 s

A Flowable source emitted an item downstream had not requested, typical of sources that cannot slow down, such as interval, PublishProcessor or Flowable.create. Pick a strategy: buffer when every item matters, drop or keep the latest when only fresh data counts.

open as a page

Why can an Android app using RxJava 3 crash with UndeliverableException after a screen is closed, and how do you handle it?

level: seniorimportance: should knowfreq 33%

basics

~20 s

A late error from a disposed or already-terminated subscription has no observer, so RxJava wraps it in UndeliverableException and calls RxJavaPlugins.onError, which by default crashes an Android app. Install RxJavaPlugins.setErrorHandler in the Application to triage such errors.

open as a page

Your Android codebase runs on RxJava 3 and the team wants coroutines and Flow: would you migrate, and how would you do it incrementally?

level: principalimportance: should knowfreq 42%

basics

~20 s

Migrate only where the payoff is real, and do it seam by seam: kotlinx-coroutines-rx3 converts in both directions (asFlow, asObservable, await, rxSingle), so a repository can switch while untouched callers keep their Rx types, with disposal and cancellation linked.

open as a page