LiveData initialization

34 Views Asked by At

I have 2 live data objects in my ViewModel:

private val _myData : LiveData<String> = myRepository.getData()
val myDataAvailable: LiveData<Boolean> = _myData.map { it != null }

As long as the repo doesn't issue a value, myDataAvailable will not be initialised. What is the best practice to set the initial value for myDataAvailable to false?

2

There are 2 best solutions below

0
Tenfour04 On BEST ANSWER

You can use the liveData builder function:

val myDataAvailable: LiveData<Boolean> = liveData {
        emit(false) 
        emitSource(_myData.map { it != null })
    }
2
Doug Stevenson On

The API documentation for MutableLiveData says there is a setValue method you can use to set the value. Just make sure you call that on the object with the initial value before it gets returned by your repository.