4

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. ¯\_(ツ)_/¯

clozach
  • 5,118
  • 5
  • 41
  • 54

1 Answers1

5

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()
}
findall
  • 2,176
  • 2
  • 17
  • 21
  • Ack! I was on vacation when you responded, and the bounty expired before I could assign it to you. Sorry, findall. Thanks for the help. Do you have any suggestions for learning RxSwift in more depth? I've been drowning in the docs and source. :-S – clozach Aug 31 '15 at 22:26