Skip to content

LiveDataExtensions

Birju Vachhani edited this page Sep 26, 2019 · 4 revisions

Examples

Observe LiveData with null check

We all know that LiveData can have null values. So when you observe them, the value is type of nullable type which forces us to perform null check before accessing it. It adds another lambda block nesting. This can be avoided by using following extensions when you don't want to deal with null values.

liveData.watch(this){ nonNullValue -> /* executed when the value is not null */ }
mutableLiveData.watch(this){ nonNullValue -> /* executed when the value is not null */ }

Convert MutableLiveData(Mutable) to LiveData(Immutable)

We tend to expose MutableLiveData instances as LiveData to other components to restrict them from changing its value. This extension does exactly the same.

mutableLiveData.immutable() // converts MutableLiveData instance to LiveData

Notify MutableLiveData About changes

When the type of LiveData is not premitive and it is object type, some changes to the properties of that object doesn't trigger action on LiveData to notify observers about the change. This extension does exactly that.

val mutableLiveData = MutableLiveData<MyCustomModel>(MyCustomModel())
mutableLiveData.value?.someProperty = "modified value"
mutableLiveData<MyCustomModel>().notify() // will notify all the observers about the change.

For more information, look at the ActivityExtensions.kt file.