clo*_*ach 4 timer reactive-programming countdown swift 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.
}
Run Code Online (Sandbox Code Playgroud)
似乎我应该能够以某种方式将计时器 observable和interval observable结合起来,但我似乎无法弄清楚这样做的正确策略。Rx 的新手,所以我愿意接受我做错了所有事情的可能性。¯\_(?)_/¯
是这样吗?
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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4153 次 |
| 最近记录: |