When I subscribe({})
to an Observable in a Singleton class, do I need to call .dispose()
method at some point? and if yes, when and where? because a singleton will remain until the App is running.
something like this (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
})
}
the subscribe()
method returns a Disposable
.
My main question is: do I need to call dispose()
at all? because I think I only can call it when the App is finished or killed, which is not necessary.
It goes to the backstack, therefore you don't need to create a new instance of CompositeDisposable every time when a fragment's view is re-created. If you have CompositeDisposable in activities, then call dispose() upon onDestroy() .
A Disposable is a stream or a link between an Observable and an Observer . A quick check of the documentation shows that it has two main methods, dispose() and isDisposed() .
CompositeDisposable is a convenient class for bundling up multiple Disposable s, so that you can dispose them all with one method call on CompositeDisposable . Instead of calling dispose() on each Disposable individually, you call CompositeDisposable#clear() to dispose all Disposable s that have been added.
The (potentially) bigger concern here is that your singleton is doing work outside the lifecycle of an Android component. If your singleton is static or hosted by your Application
, then it may be terminated abruptly when your app is in the background. If that's not a problem, then the answer to your question is no, you do not need to dispose your subscription. However, you should still be wary of doing work while your app is running in the background, unless the user expects it. (And if they do, it should probably be in a Service
or run on a schedule.) The Application
and VM can persist long after the user perceives the app to be "closed", and excessive resource consumption may lead to bad ratings and uninstalls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With