MutableLiveData with initial value

How I can initialize MutableLiveData with initial value? I'm looking for something like:

val text = MutableLiveData<String>("initial value")


Solution 1:

MutableLiveData has been updated and now it has a constructor that accepts an initial value :)

From what I can see, the constructor is available starting from this version:

implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha01'

It's a shame they haven't updated MediatorLiveData to reflect that, though.


2.1.0 is finally stable, so now you can actually see the new constructor in the documentation.

Solution 2:

You can create a handy Extension Function that does the initialization for you.

fun <T : Any?> MutableLiveData<T>.default(initialValue: T) = apply { setValue(initialValue) }

val liveData = MutableLiveData<String>().default("Initial value!")