DEV Community

Cover image for Matt's Tidbits #79 - RxLifecycle woes
Matthew Groves
Matthew Groves

Posted on • Originally published at Medium

Matt's Tidbits #79 - RxLifecycle woes

Last week, I gave a quick update on an existing tidbit. As promised, this week I have a tidbit about RxLifecycle.

The app I'm currently working on uses RxLifecycle: https://github.com/trello/RxLifecycle

It's a neat concept - instead of having to use Rx CompositeDisposable objects to clean up your subscriptions, you can use a special Rx operator to have your subscription cancelled automatically when your Android view (Fragment, Activity, etc.) transitions to a particular lifecycle state:

observable
.compose(view.bindUntilEvent(ActivityEvent.PAUSE))
.subscribe()
Enter fullscreen mode Exit fullscreen mode

RxLifecycle has some quirks - it may not call unsubscribe(), depending on the type of Rx stream you were using (Completable, Single, and Maybe types emit an error, instead of truly unsubscribing) - this leads to special error-handling code in your app that has to ignore certain types of errors that may be emitted by your Rx streams.

However, in my opinion, the worst part about RxLifecycle is that it is REALLY hard to unit test. Its bindUntilEvent method returns a final class, LifecycleTransformer (instead of an interface), which means you have to resort to using something like PowerMock to override its behavior.

I've written before about why not to use PowerMock. This should be enough to convince you that maybe RxLifecycle isn't the best choice.

However, if you're still holding on, then please read this article, from the author of RxLifecycle about why you should switch to something else:
https://blog.danlew.net/2017/08/02/why-not-rxlifecycle/

If I come up with a good way to unit test RxLifecycle without using PowerMock, I will definitely let you know! For now though, I am switching over to manually managing my disposables.

Do you know of a way to unit test RxLifecycle that doesn't require PowerMock? Let me know in the comments below! And, please follow me on Medium if you're interested in being notified of future tidbits.

This tidbit was originally delivered on August 14, 2020.

Latest comments (0)