Rxjava AndroidSchedulers.mainThread () means UI thread?

My code looks like this:

.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe ({ adapter.notifyDataSetChanged() }) 

but I got an error: only the original thread that created the hierarchy of views can touch its views. so I change it to:

 .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe ({ runOnUiThread(Runnable { adapter.notifyDataSetChanged() }) } 

It makes sense. So I'm confused. I thought .observeOn(AndroidSchedulers.mainThread()) means that the code in the subscription block works on the ui thread, but how did I get this error?

+6
source share
1 answer

The problem with the code is here:

 .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) 

You cannot subscribe to the user interface stream, as you noticed, you will get an exception:

Only the source stream that created the view hierarchy can touch its views.

What you have to do is subscribe to the I / O stream and watch the user interface stream:

 .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe () 
+6
source

All Articles