After migrating to the new Android datastore component, i have been facing problems with assigning data to mutableLiveData instances. I use the datastore component to persist viewModel data, and since reading data from the datastore file is done with a coroutine flow, i use postValue( ) methods to assign data to the mutableLiveData.However, postValue() does not assign values to mutableLiveData instances if there are no observers attached to it. Reading data from the datastore file is done Before any observers are attached, so my mutableLiveData does not receive datastore data, and i can't think of feasible workarounds.
//In myViewModel.kt
fun loadDataFromDataStore() {
myDataStore.data.map {
_myLiveData.postValue(it[myPrefsKey]?:0)
}
init {
runBlocking {
launch { loadDataFromDataStore() }
}
}
Note: Logging the values of the mutableLiveData returns null upon loading, even when logged in the main thread. See https://stackoverflow.com/a/52227632/13483506.