将 RxSwift 计时器和间隔可观察量组合成一个可完成的可观察量

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)

似乎我应该能够以某种方式将计时器 observableinterval observable结合起来,但我似乎无法弄清楚这样做的正确策略。Rx 的新手,所以我愿意接受我做错了所有事情的可能性。¯\_(?)_/¯

fin*_*all 5

是这样吗?

倒数计时器.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()
}
Run Code Online (Sandbox Code Playgroud)