首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何停止和恢复Observable.interval发送刻度

如何停止和恢复Observable.interval发送刻度
EN

Stack Overflow用户
提问于 2016-02-16 05:04:51
回答 6查看 51.9K关注 0票数 43

这将每5秒发出一次滴答。

代码语言:javascript
运行
复制
Observable.interval(5, TimeUnit.SECONDS, Schedulers.io())
            .subscribe(tick -> Log.d(TAG, "tick = "+tick));

要停止它,您可以使用

代码语言:javascript
运行
复制
Schedulers.shutdown();

但是之后所有的调度程序都会停止,以后就不可能继续计时了。我怎样才能“优雅地”停止和恢复发射?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2016-02-16 05:23:07

这里有一个可能的解决方案:

代码语言:javascript
运行
复制
class TickHandler {

    private AtomicLong lastTick = new AtomicLong(0L);
    private Subscription subscription;

    void resume() {
        System.out.println("resumed");
        subscription = Observable.interval(5, TimeUnit.SECONDS, Schedulers.io())
                                 .map(tick -> lastTick.getAndIncrement())
                                 .subscribe(tick -> System.out.println("tick = " + tick));
    }

    void stop() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            System.out.println("stopped");
            subscription.unsubscribe();
        }
    }
}
票数 42
EN

Stack Overflow用户

发布于 2017-07-24 14:06:48

前段时间,我也在寻找一种RX“计时器”解决方案,但没有一个符合我的期望。所以你可以找到我自己的解决方案:

代码语言:javascript
运行
复制
AtomicLong elapsedTime = new AtomicLong();
AtomicBoolean resumed = new AtomicBoolean();
AtomicBoolean stopped = new AtomicBoolean();

public Flowable<Long> startTimer() { //Create and starts timper
    resumed.set(true);
    stopped.set(false);
    return Flowable.interval(1, TimeUnit.SECONDS)
            .takeWhile(tick -> !stopped.get())
            .filter(tick -> resumed.get())
            .map(tick -> elapsedTime.addAndGet(1000));
}

public void pauseTimer() {
    resumed.set(false);
}

public void resumeTimer() {
    resumed.set(true);
}

public void stopTimer() {
    stopped.set(true);
}

public void addToTimer(int seconds) {
    elapsedTime.addAndGet(seconds * 1000);
}
票数 28
EN

Stack Overflow用户

发布于 2016-05-18 10:25:48

代码语言:javascript
运行
复制
val switch = new java.util.concurrent.atomic.AtomicBoolean(true)
val tick = new java.util.concurrent.atomic.AtomicLong(0L)

val suspendableObservable = 
  Observable.
    interval(5 seconds).
    takeWhile(_ => switch.get()).
    repeat.
    map(_ => tick.incrementAndGet())

您可以将switch设置为false以暂停计时,设置为true以恢复计时。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35419062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档