In this post I’ll show some useful tips for observing View changes in the background using RxAndroid and RxBinding.
Let’s start with an easy example of observing EditText changes.
This example will subscribe and observe EditText changes on the main thread. Say we want now to filter the CharSequence from the current EditText and proceed to the onNext() method only if the CharSequence is not empty? How do we achieve that in the Observable chain? We can add a function filter():
In this case function filter() doesn’t add any problems in terms of freezing the UI because it’s super fast to process. But! Say we want to have a really heavy CharSequence processing that probably will freeze the UI for a second.
We don’t want the UI thread to hang and prevent the user from typing the text, so we want to do the filter thing on another thread. In order to achieve that, we can just add a line with observeOn() before the filter function.
In this case, we filter the CharSequence on the computation thread, however now our Observer<CharSequence> will receive the result on the computation thread, too! So if we want to update some views in the onNext() method, we need to add a line after the filtering function.
Everything seems to be OK by now but there are some issues which might occur while using such approach: