Created
October 9, 2020 14:42
-
-
Save merklol/c1643fc8f99c7270a46fce2a1e5b3b9d to your computer and use it in GitHub Desktop.
StopWatch using RxJava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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