Reputation: 325
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?
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()?
Upvotes: 10
Views: 4124
Reputation: 8119
Maybe too late, But may it help others!
Observable.interval(TICK_MILLIS, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.map(v -> v * TICK_MILLIS) // use to map value to onNext func,
.takeUntil(v -> v > MAX_TICKS) // Stop Timer here.
.take() // You can use take to stop timer after N count
.subscribe(this::onNext, Log::d ,this::onComplete);
Upvotes: 1