I need a thirty-second time counter with RxSwift
.
This is a duplicate question but there is no clear answer to the questions
Asked
Active
Viewed 7,632 times
7

Behzad Moulodi
- 147
- 2
- 11
-
Not enough information. – Daniel T. Sep 22 '19 at 12:06
3 Answers
11
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")
})

SanRam
- 936
- 13
- 13
10
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)

Bart Jacobs
- 9,022
- 7
- 47
- 88
2
With 5.0 version of RxSwift you can do:
Observable<Int>.interval(.seconds(30), scheduler: MainScheduler.instance).bind { timePassed in
}.disposed(by: yourDisposeBag)

Andrew
- 471
- 3
- 13
-
This will always emit per 30 seconds if you don't kill it. – Bawenang Rukmoko Pardian Putra Sep 21 '22 at 09:48