A reactive subscription is not free. It holds a reference to the producer, all intermediate operator state, and any closure variables captured in callbacks. In Android applications, those closures routinely capture `Activity` or `Fragment` references. When the subscription outlives the component—when the user navigates away but the Observable is still live—you have a memory leak that prevents garbage collection of the entire UI subtree. RxJava's `CompositeDisposable` is the canonical Android solution: collect all `Disposable` objects returned by `subscribe()` calls into a `CompositeDisposable`, then call `disposable.clear()` in `onStop()` or `onDestroy()`. The pattern is documented explicitly in philosophical hacker's foundational 2015 analysis of RxJava subscription leaks, which remains accurate in 2025 because the underlying problem has not changed—it is a property of the subscription model, not a library bug. `takeUntil(lifecycle$)` is the RxJS equivalent: emit items until the lifecycle Observable emits (a component destroy event, a navigation event, a logout signal), then complete automatically. Angular's `UntilDestroy` decorator from `@ngneat/until-destroy` automates this pattern. Kotlin coroutines eliminate the problem structurally via `viewModelScope` and `lifecycleScope`—the coroutine scope is tied to the component lifecycle, and cancelling the scope cancels all child coroutines and Flow collectors. JDK 25's `StructuredTaskScope` extends this philosophy to the JVM server side. Scopes are lexically bounded; all tasks launched within a scope are cancelled when the scope closes. This is structured concurrency: the lifetime of concurrent work is bounded by the lexical structure of the code, not by manual resource management. Rock the JVM's coverage of JDK 25 structured concurrency describes this as the virtual thread answer to the lifecycle management problem that RxJava CompositeDisposable solves imperatively. Reactor's `takeUntilOther(cancelSignal)` and `Flux.using(resourceSupplier, fluxFactory, resourceCleanup)` provide server-side lifecycle management for streams tied to external resources like database connections or file handles.
Comments on "Declarative Subscription Lifecycle Management"
Create a free account or sign in to join the discussion.
Sign in to join the conversation