Skip to content

Instantly share code, notes, and snippets.

@ziginsider
Last active July 4, 2021 16:03
Show Gist options
  • Save ziginsider/3fccd7d80bd69dcba5846c50944386f6 to your computer and use it in GitHub Desktop.
Save ziginsider/3fccd7d80bd69dcba5846c50944386f6 to your computer and use it in GitHub Desktop.
class StopwatchViewHolder(
private val binding: StopwatchItemBinding
): RecyclerView.ViewHolder(binding.root) {
private var timer: CountDownTimer? = null
fun bind(stopwatch: Stopwatch) {
binding.stopwatchTimer.text = stopwatch.currentMs.displayTime()
if (stopwatch.isStarted) {
startTimer(stopwatch)
}
}
private fun startTimer(stopwatch: Stopwatch) {
timer?.cancel()
timer = getCountDownTimer(stopwatch)
timer?.start()
}
private fun getCountDownTimer(stopwatch: Stopwatch): CountDownTimer {
return object : CountDownTimer(PERIOD, UNIT_TEN_MS) {
val interval = UNIT_TEN_MS
override fun onTick(millisUntilFinished: Long) {
stopwatch.currentMs += interval
binding.stopwatchTimer.text = stopwatch.currentMs.displayTime()
}
override fun onFinish() {
binding.stopwatchTimer.text = stopwatch.currentMs.displayTime()
}
}
}
/*...*/
private companion object {
private const val START_TIME = "00:00:00:00"
private const val UNIT_TEN_MS = 10L
private const val PERIOD = 1000L * 60L * 60L * 24L // Day
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment