Search code examples
swifttimercountdownreactive-programmingrx-swift

Combine RxSwift timer and interval observables into a single observable with completion


I'd like to create an observable that behaves behaves something like this.

var count = 0

func setupCountdownTimer() {
  let rx_countdownTimer = CountdownTimer.observable(5)

  rx_countdownTimer >- subscribeNext {
    secondsRemaining in
    println(secondsRemaining) // prints 5, then 4, 3, 2, 1, then finally 0
    count = secondsRemaining
  }

  rx_countdownTimer >- subscribeCompleted {
    println(count) // prints 5, assuming countdownTimer stopped 'naturally'
  }
}

@IBAction func stop(sender: UIButton) {
  rx_countdownTimer.sendCompleted() // Causes 2nd println above to output, say, 3, if that's how many seconds had elapsed thus far.
}

It seems like I should be able to somehow combine a timer observable and an interval observable here, but I can't seem to figure out the correct strategy for doing this. New to Rx, so I'm open to the possibility that I'm going about it all wrong. ¯\_(ツ)_/¯


Solution

  • Is that like this?

    CountdownTimer.swift

    var timer = CountdownTimer(5)
    var count = 0
    
    func setupCountdownTimer() {
        timer.observable >- subscribeNext { n in
            println(n) // "5", "4", ..., "0" 
            self.count = n
        }
        timer.observable >- subscribeCompleted {
            println(self.count)
        }
    }
    
    @IBAction func stop(sender: UIButton) {
        timer.sendCompleted()
    }