是否建议在订阅完成工作后立即调用Disposable.dispose()? [英] Is it recommended to call Disposable.dispose() as soon as a subscription completes work?
问题描述
我有一个 Activity
,在其中创建并订阅 Single
类的多个实例(每个实例在单独的后台线程中进行一些工作).对于每个订阅,我将创建的 Disposable
实例添加到范围为 Activity
的 CompositeDisposable
实例中.当 Activity
被销毁时,我正在调用 CompositeDisposable.clear()
方法来处置 Activity
中的所有订阅.当然,这意味着所有 Disposable
实例(包括那些已完成工作的订阅实例)都在我的 Activity
中徘徊,直到 Activity
被销毁为止.
I have an Activity
in which I'm creating and subscribing to multiple instances of the Single
class (each doing some work in a separate background thread). For each subscription, I'm adding the Disposable
instance that's created to a CompositeDisposable
instance that is scoped to the Activity
. When the Activity
is destroyed I am calling the CompositeDisposable.clear()
method to dispose of all subscriptions in the Activity
. This of course means that all Disposable
instances (including those for subscriptions that have completed work) hang around in my Activity
until the Activity
is destroyed.
这还好吗,还是每当特定的 Single
实例完成工作时(即当 SingleObserver时),我应该为每个单独的订阅调用
Disposable.dispose()
接收到 onSuccess
或 onError
回调)?后一种方法的问题在于,我必须跟踪哪个 Disposable
与哪个 SingleObserver
相关联(这与使用 CompositeDisposable
的观点不符).每次 Single
实例完成工作时,是否有更好的方法来处理订阅?
Is this okay or should I be calling Disposable.dispose()
for each individual subscription every time the particular Single
instance completes work (i.e. when the SingleObserver
receives the onSuccess
or onError
callback)? The problem with the latter approach is that I have to keep track of which Disposable
is associated to which SingleObserver
(which defeats the point of using CompositeDisposable
). Is there a better approach for disposing of a subscription every time a Single
instance completes work?
推荐答案
不,您不应该. Observable
完成后, Observable
会自行处理..
这是可观察的合同的一部分:
No, you shouldn't.When an Observable
is completed, Observable
is disposed of by itself.
This is part of the Observable contract:
当Observable向其观察者发出OnError或OnComplete通知时,这将终止订阅.观察者不需要发出取消订阅"通知来终止以这种方式由观察者"终止的订阅.
When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end the subscriptions that are ended by the Observable in this way.
这篇关于是否建议在订阅完成工作后立即调用Disposable.dispose()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!