Skip to content

Instantly share code, notes, and snippets.

@yaraki
Last active December 21, 2019 07:02
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaraki/f0f449c850ec77a68352f078a11754ee to your computer and use it in GitHub Desktop.
Save yaraki/f0f449c850ec77a68352f078a11754ee to your computer and use it in GitHub Desktop.
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
Copy link
Author

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