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

Bas*_*lex 6 java android reactive-programming rx-java rx-android

我有一个静态字段

 private static Subscription timer;
Run Code Online (Sandbox Code Playgroud)

和两个静态方法:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在取消补给后猜测Observable必须停止发射物品.但它不起作用.如果函数updatePrices是

private static void update(long tick) {
    Log.d(TAG, "tick");
}
Run Code Online (Sandbox Code Playgroud)

调用removeTimer()后,将继续打印日志.

那么问题是如何正确地停止在我的观察中发射物品?

解决了

问题是双重调用setTimer().

不过我还有一个问题.任何人都可以解释为什么在第二次调用setTimer()之后,旧的计时器副本仍会继续发出项目?

Kha*_*ela 1

也许为时已晚,但愿它可以帮助其他人!

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);
Run Code Online (Sandbox Code Playgroud)