Search code examples
kotlinandroid-livedata

LiveData initialization


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?


Solution

  • You can use the liveData builder function:

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