How to stop and resume Observable.interval emiting ticks

后端 未结 7 2040
野性不改
野性不改 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:26

    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())
    

    You can set switch to false to suspend the ticking and true to resume it.

提交回复
热议问题