0

I have implemented a timer using 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();

I'd like to know :

1) How do I pause this timer? I used subscription.unsubscribe(); and it paused, but I do not know if it's a good idea.

2) How could I resume the timer? Let's say I paused it, so how could I continue the timer from where it has stopped?

reg
  • 43
  • 7

1 Answers1

0

I don't believe you can pause the timer stream after starting it. What you can do instead is use your Subscription subscription and call subscription.unsubscribe() to stop the timer. Then, when you need to restart the timer, start a new timer and add the old time to the new emissions:

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

A solution close to the one I described can be found here: How to stop and resume Observable.interval emiting ticks

Jon
  • 1,715
  • 12
  • 14