Skip to content

Instantly share code, notes, and snippets.

@tomisacat
Last active November 5, 2021 12:46
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomisacat/5699fd2cf8a18e69c31498f94787fae4 to your computer and use it in GitHub Desktop.
Save tomisacat/5699fd2cf8a18e69c31498f94787fae4 to your computer and use it in GitHub Desktop.
A simple count down timer using RxSwift
import RxSwift
func count(from: Int, to: Int, quickStart: Bool) -> Observable<Int> {
return Observable<Int>
.timer(quickStart ? 0 : 1, period: 1, scheduler: MainScheduler.instance)
.take(from - to + 1)
.map { from - $0 }
}
@tomisacat
Copy link
Author

Simple count down timer which will emit element from value from to value to.

@snowtema
Copy link

@tomisacat it works fine, but how can I pause timer and resume?

@gdxz123
Copy link

gdxz123 commented Oct 10, 2018

how to count down in background mode

@chinhnguyen
Copy link

FYI, With the latest RxSwift the last map return () and not the elapsed time

@stanfeldman
Copy link

By the way, if someone wants to do something when the timer elapses, try this:

func count(from: Int, to: Int, quickStart: Bool) -> Observable<Int> {
    return Observable<Int>
        .timer(quickStart ? 0 : 1, period: 1, scheduler: MainScheduler.instance)
        .take(from - to + 1)
        .map { from - $0 }
        .do(onCompleted: {
           // do anything when the timer elapses
       })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment