Here’s another update to rxlint, adding a new check this time for RxJava 2 that will warn you if you are using a default scheduler in an operator.

What is a default scheduler?

Consider this snippet of code:

Disposable disposable = myObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(...)

By using observeOn we make sure that this observable will emit its values on the Android main thread. Now we make a little change:

Disposable disposable = myObservable.observeOn(AndroidSchedulers.mainThread()).
                          delay(1, TimeUnit.SECONDS).subscribe(...)

Just adding a delay of one second right? Wrong, because implicitly we also changed the scheduler that this observable will emit it’s delayed value on. This is because delay() will use a scheduler to emit the value, and by default it will use the computation() scheduler. This might cause your app to crash, when you are touching views for example, or lead to subtle threading issues.

When you try the snippet above with rxlint 1.6 applied, you’ll see this:

Lint warning

The fix is simply to apply the scheduler explicitly like this:

Disposable disposable = myObservable.observeOn(AndroidSchedulers.mainThread()).
                          delay(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).subscribe(...)

This works only for RxJava 2 code because that has the required annotations for rxlint to figure out what scheduler is being used.

Thanks to Peter Tackage for suggesting this check and writing about it too! Happy linting!