Question

I have a viewmodel that triggers various objects' observables on a thread separate from the UI thread. At the same time, there's view code that is subscribing to these observables, which needs to update controls on the UI thread.

Is it better in terms of coding style to use ObserveOn to ensure the OnNext handler runs on the UI thread (i.e. add ObserveOn anywhere that can be triggered on another thread), or to have the viewmodel code responsible invoke/schedule on the UI thread (i.e. no ObserveOns needed, but one time ugly invoke/schedule lambda needed), or are either options as good as the other?

Was it helpful?

Solution

Have a look at my answer here: ObserveOn and SubscribeOn - where the work is being done.

Once you understand this, the specific answer should be clear and will depend on precisely how your Rx queries work.

In general, you want to minimize work done on the UI thread, so get off the UI thread as soon as possible after subscribing (using SubscribeOn if necessary), and get back on the UI thread as late as possible using ObserveOn. You would typically apply these to the last operator in the chain.

OTHER TIPS

I'd say it is better to use ObserveOn or some other Rx scheduling mechanism to run the work on the UI thread because then your solution is still just Rx code and still composable. If you are using Rx for the logic, but then some other non-Rx scheduling mechanism to run the final bit on the UI thread, then your code is likely more confusing as you switch mechanisms, and less composable. Sticking with ObserveOn keeps things simpler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top