4

我想创建一个行为类似这样的可观察对象。

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

似乎我应该能够以某种方式在这里结合一个可观察的计时器和一个可观察的间隔,但我似乎无法找出正确的策略来做到这一点。对 Rx 来说是新手,所以我对我做错的可能性持开放态度。¯\_(ツ)_/¯

4

1 回答 1

5

是这样的吗?

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()
}
于 2015-08-13T05:47:21.740 回答