Last active
December 21, 2019 07:02
-
-
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
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
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With a Kotlin coroutine