简体   繁体   English

ObserveOn与修改代码以在主线程上运行

[英]ObserveOn vs modifying code to run on main thread

I have a viewmodel that triggers various objects' observables on a thread separate from the UI thread. 我有一个视图模型,可在与UI线程分开的线程上触发各种对象的可观察对象。 At the same time, there's view code that is subscribing to these observables, which needs to update controls on the UI thread. 同时,有订阅这些可观察对象的视图代码,需要更新UI线程上的控件。

Is it better in terms of coding style to use ObserveOn to ensure the OnNext handler runs on the UI thread (ie add ObserveOn anywhere that can be triggered on another thread), or to have the viewmodel code responsible invoke/schedule on the UI thread (ie no ObserveOn s needed, but one time ugly invoke/schedule lambda needed), or are either options as good as the other? 就编码风格而言,使用ObserveOn来确保OnNext处理程序在UI线程上运行是否更好(即,将ObserveOn添加到可以在另一个线程上触发的任何位置),或者由ViewModel代码负责在UI线程上进行调用/调度,是否更好(即不需要ObserveOn ,但是一次丑陋的调用/调度lambda),或者其中一个选项与另一个选项一样好?

Have a look at my answer here: ObserveOn and SubscribeOn - where the work is being done . 在这里查看我的答案: ObserveOn和SubscribeOn-正在完成的工作

Once you understand this, the specific answer should be clear and will depend on precisely how your Rx queries work. 一旦您理解了这一点,具体答案就应该清楚了,并且将完全取决于您的Rx查询的工作方式。

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 . 通常,您希望最大程度地减少UI线程上的工作,因此,在订阅后尽快退出UI线程(如有必要,请使用SubscribeOn ),并尽可能晚使用ObserveOn重新回到UI线程。 You would typically apply these to the last operator in the chain. 您通常会将它们应用于链中的最后一个运算符。

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. 我想说最好使用ObserveOn或其他一些Rx调度机制在UI线程上运行工作,因为那样的话,您的解决方案仍然只是Rx代码并且仍然是可组合的。 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. 如果您将Rx用于逻辑,但随后使用其他一些非Rx调度机制来在UI线程上运行最后一位,则您的代码在切换机制时可能会更加混乱,并且难以组合。 Sticking with ObserveOn keeps things simpler. 坚持使用ObserveOn可使事情变得更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM