当我subscribe({})
到单例类中的可观察量时,我是否需要在某个时候调用.dispose()
方法? 如果是,何时何地? 因为单例将一直保留到应用程序运行。 像这样的东西(Kotlin):
@Singleton
class MySingletonClass @Inject constructor(
private val api: MyAPIManager
) {
fun fetchData() {
//subscribed inside the Singleton
api.service.getSomeDataFromAPI()
.toRxObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
//do something internally with response
},
{
//handle error internally
})
}
subscribe()
方法返回一个Disposable
。
我的主要问题是:我是否需要调用dispose()
?因为我认为我只能在应用程序完成或杀死时调用它,这是没有必要的。
这里(可能)更大的问题是,你的单例是在Android组件的生命周期之外工作。如果您的单一实例是静态的或由您的Application
托管,则当您的应用在后台运行时,它可能会突然终止。如果这不是问题,那么您问题的答案是否定的,您不需要处置您的订阅。但是,除非用户期望,否则在应用在后台运行时,仍应警惕执行工作。(如果他们这样做,它可能应该在Service
或按计划运行。在用户感知应用"关闭"后,Application
和 VM 可能会持续很长时间,过多的资源消耗可能会导致评级不佳和卸载。
您可以使用 Uber 的 autoDispose lib
myObservable
.doStuff()
.as(autoDisposable(this)) // The magic
.subscribe(s -> ...);
是的,通常我将其处理在演示者的函数stop
,该函数在onStop()
活动方法中调用