Centralized LiveData with Kotlin 1.2

Nikola Despotoski
2 min readDec 4, 2017

The very first crash I got when started Kotlin was, you may guess, UninitializedPropertyAccessException, because somewhere I used lateinit var property without prior initialization. This thought me to be more careful with fields (Java) and properties.

1.2, y tho?

In Kotlin 1.2 KProperty0<..> was introduced with really helpful property isInitialized. This inherited property denotes wither your property has been intialized in given receiver (reciever is the class that contains your property you are accessing isInitialized).

This property is annotated with @Since("1.2"), therefore you must use 1.2 version. In previous versions there is option to use isInitialized() for lazy references.

MediatorLiveData is awesome

MediatorLiveData is extremely seamless way to combine other LiveDatasources (of different types, Yas!) and all start being observed at same time.

Having separate LiveData channels for each type of event (result, error, progress, loading state etc), that is govern by one implementation on top of MediatorLiveData and takes the centralization inside BaseMediatorLiveData instead inside the Observer-end. You may say the graph you are about to see, resembles a simple LiveData for API request, you are not far from the truth.

Centralized

isInitialized comes handy when we have to decide if the other LiveData channels have been initialized or not, before they are plugged to be observed. If the observers are not initialized, there is no need to create instances of the other LiveData sources. Please note, that that sources are added for observing, before our MediatorLiveData makes the final call to be active.

Without further ado, take a look at the code. Cheers!

--

--