Reputation: 1554
I've an observable which do some magic and I am using it as a singleton in activity scope. So who ever wanna get updates, can subscribe and can get the last emitted value and new emissions.
Observable<Object> currentZoneObservable;
public Observable<Object> getCurrentZoneObservable() {
if (currentZoneObservable == null) {
currentZoneObservable = someUseCase.getObservable()
.replay(1)
.autoConnect();
}
return currentZoneObservable;
}
I am making sure all those subscribers, unsubscribe as a good citizen. I am even counting number of subscribers in doOnSubsbscribe()
and doOnUnSubscribe()
When the app goes in the background, it has 0 subscribers.
My problem is the connectableObservable
never completes and if it is doing some operation, it still keep going on with that. for eg. if it is retrying some network call when network is not available, it keeps doing it.
How can I make sure my connectableObservable
stops when there are no subscribers? My understanding is that .autoConnect()
should take care of this.
Upvotes: 1
Views: 800
Reputation: 1554
autoConnect(): Returns an Observable that automatically connects to this ConnectableObservable when the first Observer subscribes.
So even all subscribers unSubscribe, observable will still be alive.
refCount(): Returns an Observable that stays connected to this ConnectableObservable as long as there is at least one subscription to this ConnectableObservable
This will make the connectable observable stop all ongoing/future emissions.
Changing from autoConnect() to refCount() solved the issue.
Upvotes: 3
Reputation: 19381
autoConnect() does not unsubscribe when there are no observers anymore - refCount() does.
You might be interested in using a BehaviorSubject: some nice docs
Upvotes: 3