将RxSwift计时器和区间可观察值组合成一个完整的可观察对象

时间:2015-07-31 23:17:25

标签: swift timer countdown reactive-programming rx-swift

我想创建一个行为类似的observable。

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.
}

似乎我应该能够以某种方式将timer observableinterval observable组合在一起,但我似乎无法弄清楚这样做的正确策略。对Rx来说是新手,所以我很开放我可能会把它弄错。 ¯\ _(ツ)_ /¯

1 个答案:

答案 0 :(得分:4)

是这样的吗?

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