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?
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.
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...
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.
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 ()
Something like this will work:
observerable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) //works Downstream
.subscribe ({
adapter.notifyDataSetChanged()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With