Search code examples
swifttimerobservablerx-swift

RxSwift emit starting value with time interval and modify it


I need to decrease input value with every second, and print it. When value reaches 0, then it becomes 100, and decreasing process repeats, and again.

For example:

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)

I know how to use timer in Rx, but how to connect it with described case?


Solution

  • How about creating an observable from the 1 second interval and another observable from the sequence of numbers and then zipping them together? Like this:

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

    It's a bit verbose but it avoids any mutable state. HTH