0

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.

Duwang
  • 121
  • 2
  • 7
  • 1
    "postValue() does not assign values to mutableLiveData instances if there are no observers attached to it" - that is not correct, it always assigns the value one frame later (as `postValue()` posts the value to the main thread). Please include your code that isn't working – ianhanniballake Nov 14 '20 at 06:36
  • Oh, but i learnt otherwise in this SO answer https://stackoverflow.com/a/52227632/13483506. i am quite unclear, explanations are appreciated. – Duwang Nov 14 '20 at 07:07
  • That answer is wrong and has always been wrong. What are you actually trying to do with `_myLiveData`? Why aren't you using the `Flow` the DataStore provides directly? – ianhanniballake Nov 14 '20 at 07:24
  • When you state to use Flow the datastore uses directly, do you mean to type cast the flow sequence? ` val myFlow:Flow = DataStore.data.map { ...}`. I am unsure of how to type cast a flow sequence if my datastore has various data types, and postValue() sets the value of the mutableLiveData even in the absence of observers on it? Thanks in advance. – Duwang Nov 14 '20 at 08:04
  • Let's start with the first question: What are you actually trying to do with `_myLiveData`? You don't need a `MutableLiveData` when using DataStore. – ianhanniballake Nov 14 '20 at 17:22
  • I wanted to assign `_myLiveData` a value from the datastore instance, all done in a viewmodel. – Duwang Nov 15 '20 at 12:13
  • But what do you need the `_myLiveData` for? Show your code. – ianhanniballake Nov 15 '20 at 16:08

0 Answers0