【问题标题】:Pause and Resume rxJava Timer Android暂停和恢复 rxJava Timer Android
【发布时间】:2017-09-27 15:04:29
【问题描述】:

我已经使用 RxJava 实现了一个计时器。

rx.Subscription subscription = rx.Observable.interval(1000, 1000, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread()).distinct()
                    .cache().doOnNext(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                           timer.setText(String.valueOf(aLong)); )
                    .subscribe();

我想知道:

1) 如何暂停此计时器?我使用了订阅。取消订阅();它暂停了,但我不知道这是否是个好主意。

2) 我怎样才能恢复计时器?假设我暂停了它,那么如何从它停止的地方继续计时器?

【问题讨论】:

  • 既然已经内置了多种定时器,为什么还要使用 Observable?
  • 正好需要学习 ReactiveX 范式。

标签: java android


【解决方案1】:

我不相信您可以在启动计时器流后暂停它。你可以做的是使用你的Subscription subscription 并调用subscription.unsubscribe() 来停止计时器。然后,当您需要重新启动计时器时,启动一个新计时器并将旧时间添加到新排放中:

Observable.interval(1000, 1000, TimeUnit.MILLISECONDS)
            .map(aLong -> aLong + offset) // where offset was where you last stopped
            ...

可以在此处找到与我描述的解决方案相近的解决方案:How to stop and resume Observable.interval emiting ticks

【讨论】:

    猜你喜欢
    • 2013-03-04
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    相关资源
    最近更新 更多