skip to content

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%

answer

  1. the cost of two async models
  2. migrate at the seams, not the core
  3. kotlinx-coroutines-rx3 bridges both ways
  4. asFlow, asObservable, await, rxSingle
  5. nulls, subjects and threading differ

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.

solid answer

~50 s

It is a judgment call. A stable Rx codebase works and RxJava 3 is still maintained, but two async models double the review and testing burden, and many newer Jetpack APIs offer coroutine and `Flow` entry points first. If you migrate, start at the edges with `kotlinx-coroutines-rx3` as the adapter: a suspend function can `await()` a `Single` or `Completable`, an `Observable` or `Flowable` becomes a `Flow` with `asFlow()`, and a converted repository can still serve Rx callers through `asObservable()`, `asFlowable()` or `rxSingle { }`. Across the bridge, disposing the Rx side cancels the coroutine and cancelling the coroutine disposes the subscription. Convert one screen or feature at a time with tests on both sides of each seam, and watch the semantic gaps: Rx refuses `null` while `Flow` allows it, `subscribeOn` and `observeOn` become dispatchers, and subjects have no exact `Flow` twin. Make new code coroutine-first and track the remaining Rx surface until it is gone, or decide openly that a stable part stays.

code

kotlin · 26 lines
kotlin
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Single
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.rx3.asFlow
import kotlinx.coroutines.rx3.asObservable
import kotlinx.coroutines.rx3.await
import kotlinx.coroutines.rx3.rxSingle

data class User(val id: String, val name: String)
enum class Presence { ONLINE, AWAY, OFFLINE }

// The legacy Rx API, still used by screens that have not migrated.
interface LegacyUserApi {
    fun user(id: String): Single<User>
    fun presence(id: String): Observable<Presence>
}

class UserRepository(private val legacy: LegacyUserApi) {
    // Coroutine-first surface for migrated callers.
    suspend fun user(id: String): User = legacy.user(id).await()
    fun presence(id: String): Flow<Presence> = legacy.presence(id).asFlow()

    // Thin adapters for callers that still expect Rx types.
    fun userRx(id: String): Single<User> = rxSingle { user(id) }
    fun presenceRx(id: String): Observable<Presence> = presence(id).asObservable()
}

go deeper

for a junior

Know that kotlinx-coroutines-rx3 lets coroutine code await a Single and collect an Observable as a Flow, so both styles can coexist during a migration.

for a middle

Explain the bridge functions in both directions and how disposal on the Rx side and cancellation on the coroutine side are linked.

for a senior

Plan the order of conversion, find the semantic gaps such as nulls, subjects, threading and error routing, and cover each seam with tests on both sides.

for a principal

Weigh the cost of two async models against the cost of change, decide whether to migrate or freeze, and set the rule and metric that stop the migration stalling halfway.

## The decision: migrate, freeze, or keep There is no single right answer; a lead weighs the cost of change against the cost of running two asynchronous models side by side. | Option | When it fits | What it costs | |---|---|---| | **Keep Rx everywhere** | a stable app, an Rx-fluent team, little new feature work | new hires learn a second model; new Jetpack APIs need adapters | | **Freeze Rx, new code on coroutines** | active development, limited capacity for rewrites | two models for a long time; bridges at every seam | | **Migrate fully, incrementally** | the app will live for years and the team wants one model | months of steady work, regression risk at each seam | | **Big-bang rewrite** | almost never | every behaviour changes at once, with nothing to compare against | Arguments that hold up in a review: RxJava 3 is maintained (3.1.12 is current and 4.0 is only in alpha), so "unsupported" is not a reason; the real costs are cognitive load, two error-handling paths (`RxJavaPlugins` versus coroutine exception handlers), two testing toolkits (`TestObserver` and `TestScheduler` versus coroutine test utilities), and adapter code at every boundary. The question to ask is not "is Rx old" but "how much new asynchronous code will this app gain in the next two years, and in which model do we want it written". ## The bridge: kotlinx-coroutines-rx3 The `org.jetbrains.kotlinx:kotlinx-coroutines-rx3` artifact converts in both directions and links lifecycles: disposing an Rx subscription cancels the coroutine behind it, and cancelling a coroutine disposes the Rx subscription it was waiting on. | From | To | Use | |---|---|---| | `Single`, `Completable` | a suspended value | `await()` | | `Observable`, `Flowable` | `Flow` | `asFlow()` | | `Flow` | `Observable`, `Flowable` | `asObservable()`, `asFlowable()` | | a suspend block | `Single`, `Completable` | `rxSingle { }`, `rxCompletable { }` | ## An incremental order 1. **Set the rule for new code.** New features are written with coroutines and `Flow`; new public APIs do not expose Rx types. 2. **Convert leaf consumers.** ViewModels and use cases call `await()` on existing `Single` APIs and collect `asFlow()` streams. Nothing below them changes yet. 3. **Convert repositories behind adapters.** A repository gains suspend functions and `Flow` properties; Rx callers that remain get thin adapters built with `rxSingle { }` or `asObservable()`. 4. **Convert self-contained screens.** A screen whose pipeline is local, such as a search box with debounce and `switchMap`, is a good early candidate: its behaviour is easy to test before and after. 5. **Remove the bridges and the dependency last.** When no public API exposes Rx types, delete the adapters, the RxJava and RxAndroid dependencies and the `RxJavaPlugins` error handler. ## Semantics that do not translate one-for-one - **Nulls.** RxJava 3 rejects `null` items; `Flow<T?>` allows them. Adapters back into Rx require non-null element types, so map nullable values to an `Optional` or a sealed result first. - **Threading.** `subscribeOn` and `observeOn` become dispatchers and `flowOn`, which follow different rules; re-check every place that touches views. - **Subjects.** `BehaviorSubject` is closest to `StateFlow`, which, unlike it, skips equal consecutive values; `PublishSubject` maps to a `SharedFlow` with a chosen replay and buffer. Neither is a drop-in. - **Error routing.** RxJava's global `RxJavaPlugins` hook has no coroutine counterpart; failures follow structured concurrency and the coroutine exception handlers instead, so crash reporting must be re-checked at each seam. - **Backpressure.** A `Flowable`'s request-based demand becomes suspension; overflow strategies such as `onBackpressureLatest` need an explicit `Flow` equivalent at the seam. ## Keeping it safe - Cover each seam with tests on both sides: the Rx contract (`TestObserver`) before the change, the coroutine contract after. - Make regrowth visible: a lint rule or review checklist that rejects new Rx types in public signatures. - Track the remaining Rx surface, such as modules and public functions exposing Rx types, and review the trend each quarter. - Run both versions of a converted screen behind a feature flag for a release when its behaviour is risky, so a regression can be switched off without a rollback. - When the number stops falling, decide openly: finish the job, or declare the remaining area frozen and keep its bridges deliberately.

  • What happens to the Rx subscription when the coroutine collecting observable.asFlow() is cancelled?
    It is disposed. The bridge ties the lifecycles together: cancelling the collector, for example when its scope ends with the screen, disposes the upstream subscription, and disposing an `Observable` built with `asObservable()` or a `Single` built with `rxSingle { }` cancels the coroutine behind it. The coroutine side needs no extra `CompositeDisposable` bookkeeping.
  • Which RxJava constructs have no exact Flow equivalent, and why does that matter for migration?
    Subjects: a `BehaviorSubject` is closest to `StateFlow`, which, unlike it, skips equal consecutive values, and a `PublishSubject` to a `SharedFlow` with chosen replay and buffer. `Single`, `Maybe` and `Completable` become suspend functions. Each substitution changes behaviour in edge cases, so it needs its own test rather than a mechanical rename.
  • How do you tell whether the migration is finished or has stalled?
    Track the remaining Rx surface, such as modules and public functions that still expose Rx types, plus the bridge calls at the seams, and stop regrowth with a lint rule or review checklist. When the count stops falling, decide openly whether to finish or to freeze the rest, rather than keeping two models by default.

  • Migration means rewriting the whole Rx layer in one release.
  • Flow is a renamed Observable, so operators and threading translate one-for-one.
  • After bridging with asFlow(), you must still dispose the Rx subscription by hand.
  • RxJava 3 is unmaintained, so keeping it is never a reasonable choice.
  • A BehaviorSubject and a StateFlow behave identically, even for repeated equal values.

Assumes RxJava 3.1.12 bridged with kotlinx-coroutines-rx3; RxJava 4.0 is still in alpha and its APIs are not covered.