In this article I want to show how to avoid redundant switching of threads (schedulers, exactly, in terms of RxJava) when using operators, which require scheduler to work on.

Take for example operator debounce. I often use it, to drop frequently changing values on UI and use only latest. This operator by default operates on computation scheduler, because it needs to schedule timeouts after which to emit value.

For example, it's usage may look like this:

  .debounce(500L, TimeUnit.MILLISECONDS)

I used RxBinding for observing changes in EditText field, but it can be any other observable. So this sequence can written in a shorter and better way:

  .debounce(500L, TimeUnit.MILLISECONDS, AndroidScheduler.mainThread())

This way, we avoid switching of threads, from computation to main, therefor we have better performance.

How does it work? Will it block main thread?

No! Because Android provides mechanism for scheduling delayed tasks on threads: Handler and Looper, which of course are internally used by RxAndroid.

Same approach can be used with such operators as timer, interval, delay if you want them to work on main thread.

This is a very simple, but useful example, which haven't came into my mind, even though I've been using RxJava for quite some time, so I decided to share it.


comments powered by Disqus