Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjava AndroidSchedulers.mainThread() means UI thread?

My code is like this:

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

but i got an error: Only the original thread that created a view hierarchy 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 am confused. I had thought the .observeOn(AndroidSchedulers.mainThread()) means the code in the subscribe block runs on ui thread, but how I got this error?

like image 232
Allen Vork Avatar asked Jan 27 '16 02:01

Allen Vork


People also ask

What are schedulers in RxJava?

Android Scheduler — This Scheduler is provided by rxAndroid library. This is used to bring back the execution to the main thread so that UI modification can be made. This is usually used in observeOn method.

What is ObserveOn in RxJava?

ObserveOn specify the Scheduler on which an observer will observe this Observable. So basically SubscribeOn is mostly subscribed (executed) on a background thread ( you do not want to block the UI thread while waiting for the observable) and also in ObserveOn you want to observe the result on a main thread...

Why schedulers and how RxJava internally works with them?

RxJava Schedulers. Threading in RxJava is done with help of Schedulers. Scheduler can be thought of as a thread pool managing 1 or more threads. Whenever a Scheduler needs to execute a task, it will take a thread from its pool and run the task in that thread.


2 Answers

The problem is with the code here:

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

You can not subscribe on the UI thread as you noticed, you'll get an exception:

Only the original thread that created a view hierarchy can touch its views.

What you should do is to subscribe on I/O thread and observe on UI thread:

.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe ()
like image 76
mmBs Avatar answered Oct 12 '22 22:10

mmBs


Something like this will work:

observerable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) //works Downstream
.subscribe ({
   adapter.notifyDataSetChanged()
})
like image 29
keshav Avatar answered Oct 13 '22 00:10

keshav