7

I need a thirty-second time counter with RxSwift. This is a duplicate question but there is no clear answer to the questions

Behzad Moulodi
  • 147
  • 2
  • 11

3 Answers3

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