The problem with RxAndroid’s AndroidSchedulers.mainThread()


There is a really good short video by Ray Ryan from Square about how adding code like the following causes problems:

newChild.post(	
    new Runnable(){
        @Override public void run(){	
               // do something with newChild	
        }
    }
);

Which at some point usually leads to you getting a null pointer exception.

The solution is to keep the main thread synchronous, and these problems wont happen. Turns out when using RxAndroid if you use the Android Scheduler.mainThread scheduler you end up introducing not only a post, but a postDelayed runnable. I had to see this for myself so I went and looked at the source code and sure enough it’s there. Ray gives a few possible solutions to this problem(change the scheduler so that it doesn’t post if it is already on the mainthread, but apparently this causes problems such as missing exceptions as a result)

Ray/Square’s solution has been to just keep model updates on the main thread. Everything past that can be on some other thread. This gets around the problem of having flickering due to model object changes happening on different screen updates.

The other great takeaway from this is to only use ObserveOn(AndroidSchedulers.mainThread()) when necessary as it will always introduce this postDelayed code, even if you rx logic doesn’t involve running on some other thread.

Again, I highly recommend checking out the video, it’s short roughly 7 minutes.

Leave a Reply

Your email address will not be published. Required fields are marked *