Reputation: 1546
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?
Upvotes: 15
Views: 11619
Reputation: 35
Something like this will work:
observerable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) //works Downstream
.subscribe ({
adapter.notifyDataSetChanged()
})
Upvotes: 1
Reputation: 8559
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 ()
Upvotes: 13