【问题标题】:RxSwift emit starting value with time interval and modify itRxSwift 以时间间隔发出起始值并修改它
【发布时间】:2019-01-02 10:40:37
【问题描述】:

我需要每秒减少输入值,然后打印出来。 当值达到 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 中使用计时器,但是如何将它与描述的案例联系起来?

【问题讨论】:

    标签: swift timer observable rx-swift


    【解决方案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 value>>>> : ",self.start)
              })
    }
    

    【讨论】:

      【解决方案2】:

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

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

      它有点冗长,但它避免了任何可变状态。高温

      【讨论】:

      • 这是我一直在寻找的东西,谢谢 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 2022-11-22
      • 2021-11-28
      • 2018-06-18
      相关资源
      最近更新 更多