« Create your own LiveData implementation

1package com.anish.createlivedatafromscratch
2
3import androidx.lifecycle.Lifecycle
4import androidx.lifecycle.LifecycleObserver
5import androidx.lifecycle.LifecycleOwner
6import androidx.lifecycle.OnLifecycleEvent
7
8class MyOwnLiveData<T> {
9
10 private var dataHolder: T? = null
11 private val hashMapOfObservers: HashMap<(T?) -> Unit, LifeCycleObserverWrapper> = HashMap()
12
13 fun postValue(value: T) {
14 dataHolder = value
15 hashMapOfObservers.values.forEach {
16 if (it.lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
17 it.observer.invoke(dataHolder)
18 }
19 }
20 }
21
22 fun getValue() = dataHolder
23
24 fun addObserver(lifecycleOwner: LifecycleOwner, observer: (T?) -> Unit) {
25 LifeCycleObserverWrapper(lifecycleOwner, observer).apply {
26 this.lifecycleOwner.lifecycle.addObserver(this)
27 hashMapOfObservers[observer] = this
28 }
29
30 }
31
32 fun removeObserver(observer: (T?) -> Unit) {
33 hashMapOfObservers[observer]?.run {
34 this.lifecycleOwner.lifecycle.removeObserver(this)
35 }
36 }
37
38 fun updateValue(observer: (T?) -> Unit) {
39 observer.invoke(dataHolder)
40 }
41
42 private inner class LifeCycleObserverWrapper(
43 val lifecycleOwner: LifecycleOwner, val observer: (T?) -> Unit
44 ) : LifecycleObserver {
45
46 @OnLifecycleEvent(Lifecycle.Event.ON_START)
47 fun doOnStart() {
48 updateValue(observer)
49 }
50
51 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
52 fun doOnResume() {
53 updateValue(observer)
54 }
55
56 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
57 fun doOnDestroy() {
58 removeObserver(observer)
59 }
60 }
61}

For full code please refer:

1https://github.com/anishakd4/CreateLiveDataFromScratch