在iOS上,对于MVVM中的DisposeBag,是否可以放在ViewModel中? [英] On iOS, for the DisposeBag in MVVM, can it be placed in ViewModel?
问题描述
我是 RxSwift 的新手,在这里我想问一个关于 DisposeBag 应该放在哪里的问题.
I am new to RxSwift and here I would like to ask a question about where should the DisposeBag be.
我的情况是,我检索了一个在 tableview 中显示的项目列表,每个项目都有自己的标志来指示它是否被选中.
My case is, I have retrieve a list of items being displayed in a tableview, and each of them will have its own flag to indicate if it is selected.
所以我不只是将结果列表绑定到 tableview.我需要一些逻辑来在用户通过 tableview 导航时在本地编辑列表.
So I am not just binding the result list to the tableview. I need to have some logic which editing the list on local while user navigate via the tableview.
我在 ViewModel
中创建了一个实例 Variable([Item])
但是如果我将逻辑放在 ViewModel
中,则 >DisposeBag
是必需的.
I have created an instance Variable([Item])
in the ViewModel
but if I place the logic in the ViewModel
a DisposeBag
is needed.
经过一些谷歌搜索后,大多数具有 Variable
实例的 MVVM+RxSwift 示例将 DisposeBag
放在 ViewModel
中,但有人说它应该只放在 ViewController
中.真的吗?如何在 ViewModel
中监听 Observable
以便我的业务逻辑可以放在 ViewModel
中?
After having some googling, most of the examples of MVVM+RxSwift which have instances of Variable
place the DisposeBag
in ViewModel
but some say it should only be placed in ViewController
. Is that true? How can I listen the Observable
in ViewModel
so that my business logic can be placed in ViewModel
?
推荐答案
DisposeBag
通常应该不放在 ViewModel 中,除非有充分的理由.
A DisposeBag
more often than not should not be placed in a ViewModel unless there's a good reason.
通常,DisposeBag
旨在将订阅与其所有者联系起来.通常情况下,ViewModel 不会创建任何订阅,而只是提供 Observable 以便消费者可以订阅它们(例如 ViewController).
In general a DisposeBag
is meant to tie subscriptions to their owner. It is usually not the case that the ViewModel creates any subscriptions, but merely provides Observables so a consumer could subscribe to them (for example a ViewController).
这意味着 ViewController 通常是保存 DisposeBag
的控制器,因为它通常是使用订阅的控制器(而不是 ViewModel 本身).
That means the ViewController is the one to usually hold the DisposeBag
, as its usually the one that uses the subscriptions (and not the ViewModel itself).
这篇关于在iOS上,对于MVVM中的DisposeBag,是否可以放在ViewModel中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!