Simple timer with rxSwift

jerrygdm picture jerrygdm · Dec 16, 2016 · Viewed 16.6k times · Source

I'm trying to reproduce a simple timer with RxSwift.

I have a pause/play button only that works for pause and resume.

        gameTimer = Observable<NSInteger>.interval(1, scheduler: MainScheduler.instance)
            .subscribeNext({ sec -> Void in
            print("\(sec) s")
        }).addDisposableTo(disposeBag!)


            pauseResumeButton.rx_tap
            .map{ !self.isRunning.value }
            .startWith(true)
            .bindTo( isRunning )
            .addDisposableTo(disposeBag!)

isRunning is an Variable<Bool> obviously. I can stop the timer settings disposeBag = nil but I cannot pause it....itried to filter events but the count obviously continues to grow...

Can anyone help me? Thanks!

Answer

beeth0ven picture beeth0ven · Dec 17, 2016

A little trick:

class ViewController: UIViewController {

    let isRunning = Variable(true)

    override func viewDidLoad() {
        super.viewDidLoad()

        isRunning.asObservable()
            .debug("isRunning")
            .flatMapLatest {  isRunning in
                isRunning ? Observable<Int>.interval(1, scheduler: MainScheduler.instance) : .empty()
            }
            .flatMapWithIndex { (int, index) in Observable.just(index) }
            .debug("timer")
            .subscribe()
            .addDisposableTo(disposeBag)

        navigationItem.rightBarButtonItem!.rx.tap
            .subscribe(onNext: { [unowned self] in
                self.isRunning.value = !self.isRunning.value
            })
            .addDisposableTo(disposeBag)

    }
}

Result:

2016-12-17 20:53:11.408: timer -> subscribed
2016-12-17 20:53:11.414: isRunning -> subscribed
2016-12-17 20:53:11.415: isRunning -> Event next(true)
2016-12-17 20:53:12.503: timer -> Event next(0)
2016-12-17 20:53:13.488: timer -> Event next(1)
2016-12-17 20:53:14.488: timer -> Event next(2)
2016-12-17 20:53:15.488: timer -> Event next(3)
2016-12-17 20:53:16.154: isRunning -> Event next(false)
2016-12-17 20:53:23.155: isRunning -> Event next(true)
2016-12-17 20:53:24.223: timer -> Event next(4)
2016-12-17 20:53:25.229: timer -> Event next(5)
2016-12-17 20:53:26.228: timer -> Event next(6)
2016-12-17 20:53:27.220: timer -> Event next(7)
2016-12-17 20:53:28.225: timer -> Event next(8)
2016-12-17 20:53:29.221: timer -> Event next(9)
2016-12-17 20:53:29.971: isRunning -> Event next(false)