How to dispose Single observer in RxJava2 when used in background and not in Activity/Fragment

Viewed 2127

How to dispose Single observer in RxJava2 when used in background and not in Activity/Fragment.

I know if Single used in Activity/Fragment then it can be added in composite disposer and dispose it in Activity/Fragment's onDestroy method.

But how to dispose it when it is called from somewhere else?

Also what are the other ways to dispose Single if it is called from Activity/Fragment and we want to dispose it before onDestroy being called?

1 Answers

Two of the default observers (ConsumerSingleObserver and BiConsumerSingleObserver) that are returned by Single when you subscribe dispose themselves onError and onSuccess. If you pass in your own custom SingleObserver, you need to decide when to dispose it.

A Single will call only one of these methods, and will only call it once. Upon calling either method, the Single terminates and the subscription to it ends. (http://reactivex.io/documentation/single.html)

In some cases you may want to dispose of the SingleObserver before it disposes itself, in which case you just need to call dispose on a Disposable returned by a subscribe. When and where you call it really depends on your particular situation.

If your Single doesn't complete before your life-cycled object gets destroyed (e.g. HTTP calls), you must dispose the observer in a destroy callback of the life-cycled object.

Related