LiveData
:red_circle:ㅤ[ARTICLE] How I made my own LiveData!
Install / Use
/learn @hitanshu-dhawan/LiveDataREADME
Full article here: https://medium.com/androidiots/how-i-made-my-own-livedata-1faf4a45520
LiveData
<br>LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
class LiveData<T> {
private var mValue: T? = null
private val mObservers: HashMap<(T?) -> Unit, LiveDataLifecycleObserver> = HashMap()
fun setValue(value: T) {
mValue = value
for (lifecycleObserver in mObservers.values) {
val owner = lifecycleObserver.owner
if (owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))
notifyChange(lifecycleObserver)
}
}
fun getValue(): T? {
return mValue
}
fun observe(owner: LifecycleOwner, observer: (T?) -> Unit) {
val lifecycleObserver = LiveDataLifecycleObserver(owner, observer)
mObservers[observer] = lifecycleObserver
owner.lifecycle.addObserver(lifecycleObserver)
}
fun removeObserver(observer: (T?) -> Unit) {
val lifecycleObserver = mObservers.remove(observer)
lifecycleObserver?.owner?.lifecycle?.removeObserver(lifecycleObserver)
}
private fun notifyChange(lifecycleObserver: LiveDataLifecycleObserver) {
lifecycleObserver.observer.invoke(mValue)
}
private inner class LiveDataLifecycleObserver(
val owner: LifecycleOwner, val observer: (T?) -> Unit
) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private fun onStarted() {
notifyChange(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private fun onResumed() {
notifyChange(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private fun onDestroyed() {
removeObserver(observer)
}
}
}
Related Skills
node-connect
341.6kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
84.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
341.6kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
84.6kCommit, push, and open a PR
