Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I dispose disposables in a Singleton class ( Android RxJava 2 )

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.

like image 470
Amir Khorsandi Avatar asked Jul 23 '18 08:07

Amir Khorsandi


People also ask

When should I dispose of disposable Rxjava?

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() .

What is disposable in Android Studio?

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() .

What is the use of CompositeDisposable?

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.


1 Answers

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.

like image 79
StackOverthrow Avatar answered Oct 09 '22 16:10

StackOverthrow