简体   繁体   English

Android RxJava Observable.interval()不会停止发出项目

[英]Android RxJava Observable.interval() doesn't stop emitting items

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. 在取消补给后猜测Observable必须停止发射物品。 However it doesn't work. 但它不起作用。 If function updatePrices is 如果函数updatePrices是

private static void update(long tick) {
    Log.d(TAG, "tick");
}

Logs continue to be printed after calling removeTimer(). 调用removeTimer()后,将继续打印日志。

So the question is how to stop emitting items in my observable correctly? 那么问题是如何正确地停止在我的观察中发射物品?

Solved 解决了

The issue was in double calling of setTimer(). 问题是双重调用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()? 任何人都可以解释为什么在第二次调用setTimer()之后,旧的计时器副本仍会继续发出项目?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM