Let's assume I have a following case for Android:
- Request list of groups from network
- Show some UI elements for each group
- Request items for each group
- Show UI elemets for each item
I want to do this using RxJava:
webService.requestGroups()
.flatMap(group -> {
view.showGroup(group);
return webService.requestItems(group);
})
.toList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> view.showItems(items));
As you can see I have 2 calls for view objects, each of them must be executed on main thread. And 2 calls for webService, which must be executed on background thread.
The problem with this code: first call to view will be executed on background which cause an Android RuntimeException (Only original thread may touch views or something) If I transfer .observeOn
to the beginning of chain - second webService call will be executed in main thread.
How can I "swim" through threads multiple times in RxJava chain?