How to stop and resume Observable.interval emiting ticks

后端 未结 7 2044
野性不改
野性不改 2020-12-13 06:32

This will emit a tick every 5 seconds.

Observable.interval(5, TimeUnit.SECONDS, Schedulers.io())
            .subscribe(tick -> Log.d(TAG, "tick = &qu         


        
7条回答
  •  感动是毒
    2020-12-13 07:15

    Some time ago, I was also looking for kind of RX "timer" solutions, but non of them met my expectations. So there you can find my own solution:

    AtomicLong elapsedTime = new AtomicLong();
    AtomicBoolean resumed = new AtomicBoolean();
    AtomicBoolean stopped = new AtomicBoolean();
    
    public Flowable 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);
    }
    

提交回复
热议问题