Skip to content

Instantly share code, notes, and snippets.

@yaraki

yaraki/ClockLiveData.kt

Last active Dec 21, 2019
Embed
What would you like to do?
This LiveData provides the time in hh:mm:ss format, updating the value every second
package io.github.yaraki.dependencyinjection
import android.arch.lifecycle.LiveData
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.text.format.DateFormat
import java.util.*
class ClockLiveData : LiveData<CharSequence>() {
private var handler = Handler(Looper.getMainLooper())
private val calendar = Calendar.getInstance()
private val ticker: Runnable = object : Runnable {
override fun run() {
if (!hasActiveObservers()) {
return
}
calendar.timeInMillis = System.currentTimeMillis()
value = DateFormat.format("hh:mm:ss", calendar)
val now = SystemClock.uptimeMillis()
val next = now + (1000 - now % 1000)
handler.postAtTime(this, next)
}
}
override fun onActive() {
super.onActive()
ticker.run()
}
}
@yaraki

This comment has been minimized.

Copy link
Owner Author

@yaraki yaraki commented Jul 5, 2018

With a Kotlin coroutine

package io.github.yaraki.coroutineex

import android.arch.lifecycle.LiveData
import android.text.format.DateFormat
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import java.util.*

class ClockLiveData : LiveData<CharSequence>() {

    private val calendar = Calendar.getInstance()

    override fun onActive() {
        super.onActive()
        launch(UI) {
            while (isActive && hasActiveObservers()) {
                val now = System.currentTimeMillis()
                calendar.timeInMillis = now
                value = DateFormat.format("hh:mm:ss", calendar)
                delay(1000L - (now % 1000L))
            }
        }
    }

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