Skip to content

Instantly share code, notes, and snippets.

@merklol
Created October 9, 2020 14:42
Show Gist options
  • Save merklol/c1643fc8f99c7270a46fce2a1e5b3b9d to your computer and use it in GitHub Desktop.
Save merklol/c1643fc8f99c7270a46fce2a1e5b3b9d to your computer and use it in GitHub Desktop.
StopWatch using RxJava
class StopWatch {
private val disposableBag = CompositeDisposable()
var onTick: (String) -> Unit = {}
var elapsedTime: Long = 0
companion object {
const val INITIAL_VALUE = "00:00:00"
}
fun start() {
disposableBag.add(
Observable.interval(1000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.subscribe {
onTick.invoke(formatElapsedTime(it))
})
}
fun stop() {
disposableBag.clear()
}
private fun formatElapsedTime(elapsed: Long): String {
val hours = elapsed / 3600
val minutes = (elapsed % 3600) / 60
val seconds = elapsed % 60
return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment