I have a static field
private static Subscription timer;
and two static methods:
public static void setTimer() {
timer = Observable.interval(2, TimeUnit.SECONDS, Schedulers.computation())
.doOnNext(tick -> update(tick))
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
}
public static void removeTimer() {
if (timer != null && !timer.isUnsubscribed()) {
timer.unsubscribe();
timer = null;
}
}
Guessing after unsubsription Observable have to stop emitting items. However it doesn't work. If function updatePrices is
private static void update(long tick) {
Log.d(TAG, "tick");
}
Logs continue to be printed after calling removeTimer().
So the question is how to stop emitting items in my observable correctly?
Solved
The issue was in double calling of setTimer().
However I still have a question. Can anybody explain why is the old copy of timer still continues to emit items after the second call of setTimer()?
removeTimer
is called. Could you verify that you are not calling thesetTimer
again from somewhere after theremoveTimer
call? – BacksightsetTimer
call creates a new subscription(timer
) thereby replacing the old one. When you callremoveTimer
it is applied to the last subscription, thereby leaking others. You can avoid that by checking for null before creating a new one.if(timer == null || timer.isUnsubscribed()){ timer=...}
– Backsight