RxJava 1 -> RxJava 2 (Disposing Subscriptions)
Article Summary
Migrating from RxJava 1 to RxJava 2? The biggest gotcha isn't what you think—it's how you dispose of subscriptions.
Instacart engineer Kaushik Gopal breaks down the trickiest part of the RxJava 2 migration: managing subscription lifecycles. The Reactive Streams spec changed everything about how you prevent memory leaks in Android apps.
Key Takeaways
- Publisher.subscribe() now returns void, not Subscription like RxJava 1
- Subscriptions renamed to Disposables; use CompositeDisposable instead of CompositeSubscription
- subscribeWith() method lets you treat DisposableSubscriber as both Subscriber and Disposable
- Use .clear() not .dispose() on CompositeDisposable to allow reuse
- Lambda subscriptions still return Disposable; only Subscriber objects need workarounds
RxJava 2's Reactive Streams compliance broke the old subscription pattern, but DisposableSubscriber and subscribeWith() restore the convenience Android devs need for lifecycle management.
About This Article
RxJava 2 adopted the Reactive Streams specification, which changed Publisher.subscribe() to return void instead of a Subscription. This broke the RxJava 1 pattern where developers collected subscriptions in CompositeSubscription to manage lifecycles and prevent memory leaks.
Kaushik Gopal explains that RxJava maintainers added the subscribeWith() method and DisposableSubscriber class to address this. DisposableSubscriber implements both the Subscriber interface and Disposable interface, so developers can manage subscribers as disposables through CompositeDisposable.
The Reactive Streams compliance change created a problem, but the new helper classes fixed it. Android developers can now use the same lifecycle-based subscription disposal patterns from RxJava 1 while still following the external specification.