Using RxJava in a project has many advantages, but learning rx can be a bit challenging. And with learning, it’s easy to make mistakes :)
One common problem is not handling
onError(). Consider the following snippet:
This may look simple; subscribe to an observable and get the first item only, but there’s a catch. If the observable doesn’t emit any items (it just completes), the
first() operator will throw
Since there’s no handing for the
onError() notification, the snippet above will throw an exception at runtime and will therefore crash. When that crash happens on a background thread, it will be impossible to figure out
what subscription caused it. Will that ever happen? I don’t know, but the issue is that it might depending on the observable that is being subscribed to.
Even if you do know that
first() throws an exception, it’s pretty easy to forget handling the error that might occur. That’s where
rxlint comes in.
The rxlint check
rxlint is currently a single lint rule that detects a subscription without a handler for
rxlint to your project is easy. Just add the
compile 'nl.littlerobots.rxlint:rxlint:1.0 dependency to your code and Android Studio will show you when you forget to handle
Note a couple of things:
- rxlint will only check your Android code currently. If you have separate Java modules, you can run the lint check on those in Android Studio, but this integration is not perfect.
- rxlint will flag observables that never throw any errors, for example when you are using the
onErrorXXXoperators. As with any lint check, you can suppress the lint error in that case.
- Even though the
rxlintdependency is specified in
compilescope, no code is added to your project at any time.
rxlint is open source under the Apache License. Check out the project site for more info and add
rxlint to your project to slay those errors!