Instacart Kaushik Gopal Jun 21, 2017

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

Critical Insight

RxJava 2's Reactive Streams compliance broke the old subscription pattern, but DisposableSubscriber and subscribeWith() restore the convenience Android devs need for lifecycle management.

The article reveals a critical difference between .clear() and .dispose() that could break your entire subscription management strategy.

About This Article

Problem

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.

Solution

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.

Impact

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.