简体   繁体   中英

How to set due time in timer(_:period:scheduler:)

I have learned RxSwift for a period of time by following the book named Reactive Programming with swift. There are some tutorials about timer operator that I cannot understand

let elementsPerSecond = 1
let delayInSeconds = 2
let sourceObservable = PublishSubject<Int>()

var current = 1
let timer = DispatchSource.timer(interval: 1.0 / Double(elementsPerSecond), queue: .main) {
    sourceObservable.onNext(current)
    sourceObservable2.onNext(current)
    current = current + 1
}

_ = sourceObservable.subscribe(sourceTimeline)

_ = sourceObservable
.delay(RxTimeInterval(delayInSeconds), scheduler: MainScheduler.instance)
.subscribe(delayedTimeline)

_ = Observable<Int>
.timer(RxTimeInterval(0), scheduler: MainScheduler.instance)
.flatMap { _  in
    return sourceObservable.delay(RxTimeInterval(delayInSeconds), scheduler: MainScheduler.instance)
}
.subscribe(timerTimeline)

But the result is very strange: 在此处输入图片说明

The third view is timerTimeline and it was second behind second timeline which is delayedTimeline. So where is the second goes? What's more, the first element was ignored by the timerTimeline. I don't know how to use the timer operator and could anyone tell me the reason, thanks.

It is a strange example indeed, especially the first half of it. As for your questions I guess the missing second is a mistake (should be '.timer(RxTimeInterval(1)' ), and the first element ('1') is skipped because flatMap() was executed only when it was already gone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM