RxSwift随时间间隔发出起始值并对其进行修改

时间:2019-01-02 10:40:37

标签: swift timer observable rx-swift

我需要每秒减少输入值,然后打印出来。 当值达到0时,它将变为100,然后重复执行递减过程。

例如:

Given value: 
-> 234
Timer starts decreasing with every second
 -> 233
 -> 232 
...
 -> 1
 -> 0 and the whole process repeats,

but starts with value 100 
(and again decreasing, reaches 0, starting from 100)

我知道如何在Rx中使用计时器,但是如何将其与所描述的情况联系起来?

2 个答案:

答案 0 :(得分:1)

您只需要一个具有初始值的变量,如下所示:

var start = 234

func startTimer() {
     _ = Observable<Int>
          .timer(0, period: 1, scheduler: MainScheduler.instance)
          .subscribe(onNext: { _ in
              self.start -= 1
              if self.start <= 0 {
                  self.start = 100
              }
              print("Timer valuse>>>> : ",self.start)
          })
}

答案 1 :(得分:1)

如何从1秒间隔创建一个可观察值,并从数字序列中创建另一个可观察值,然后将它们压缩在一起?像这样:

let interval = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
let startValue1 = 234
let startValue2 = 100

let range1 = Observable
    .range(start: 0, count: startValue1 + 1)
    .map { startValue1 - $0 }

let range2 = Observable
    .range(start: 0, count: startValue2 + 1)
    .map { startValue2 - $0 }
    .repeatWithBehavior(.immediate(maxCount: .max))
    .subscribeOn(SerialDispatchQueueScheduler(qos: .background))

Observable.zip(
    interval,
    range1.concat(range2))
    .subscribe(onNext : { (_, remainingTime) in
        print("\(remainingTime)")
    })

这有点冗长,但是避免了任何可变状态。 HTH