I need a thirty-second time counter with RxSwift
.
This is a duplicate question but there is no clear answer to the questions
3 Answers
Better approach for existing answer.
let countDown = 15 // 15 seconds
Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
.take(countDown+1)
.subscribe(onNext: { timePassed in
let count = self.countDown - timePassed
print(count)
}, onCompleted: {
print("count down complete")
})
-
-
1
This is an even cleaner solution in my opinion (Swift 5.3). The onNext
closure receives the time remaining so there is no need to perform a calculation. This also makes it easier to use the takeUntil
operator to terminate the subscription when the value is equal to 0
.
let countdown = 30
Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
.map { countdown - $0 }
.takeUntil(.inclusive, predicate: { $0 == 0 })
.subscribe(onNext: { value in
print(value)
}, onCompleted: {
print("completed")
}).disposed(by: disposeBag)
With 5.0 version of RxSwift you can do:
Observable<Int>.interval(.seconds(30), scheduler: MainScheduler.instance).bind { timePassed in
}.disposed(by: yourDisposeBag)
-
This will always emit per 30 seconds if you don't kill it. Sep 21, 2022 at 9:48