« Create your own LiveData implementation
1package com.anish.createlivedatafromscratch23import androidx.lifecycle.Lifecycle4import androidx.lifecycle.LifecycleObserver5import androidx.lifecycle.LifecycleOwner6import androidx.lifecycle.OnLifecycleEvent78class MyOwnLiveData<T> {910 private var dataHolder: T? = null11 private val hashMapOfObservers: HashMap<(T?) -> Unit, LifeCycleObserverWrapper> = HashMap()1213 fun postValue(value: T) {14 dataHolder = value15 hashMapOfObservers.values.forEach {16 if (it.lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {17 it.observer.invoke(dataHolder)18 }19 }20 }2122 fun getValue() = dataHolder2324 fun addObserver(lifecycleOwner: LifecycleOwner, observer: (T?) -> Unit) {25 LifeCycleObserverWrapper(lifecycleOwner, observer).apply {26 this.lifecycleOwner.lifecycle.addObserver(this)27 hashMapOfObservers[observer] = this28 }2930 }3132 fun removeObserver(observer: (T?) -> Unit) {33 hashMapOfObservers[observer]?.run {34 this.lifecycleOwner.lifecycle.removeObserver(this)35 }36 }3738 fun updateValue(observer: (T?) -> Unit) {39 observer.invoke(dataHolder)40 }4142 private inner class LifeCycleObserverWrapper(43 val lifecycleOwner: LifecycleOwner, val observer: (T?) -> Unit44 ) : LifecycleObserver {4546 @OnLifecycleEvent(Lifecycle.Event.ON_START)47 fun doOnStart() {48 updateValue(observer)49 }5051 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)52 fun doOnResume() {53 updateValue(observer)54 }5556 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)57 fun doOnDestroy() {58 removeObserver(observer)59 }60 }61}
For full code please refer:
1https://github.com/anishakd4/CreateLiveDataFromScratch