I need to have some data loaded from a database in my View Model when is it created. Since the data comes in the form of a Flow, I'm passing it to a lateinit variable using collect. However, I need to further process the data after it is loaded in it, but I don't know how to wait for the data to actually be loaded.
This what I have so far:
class MyViewModel: ViewModel() {
...
private var _state = MutableStateFlow(MyState())
var state = _state.asStateFlow()
private val myDataSource: MyDataSource
lateinit var loadedData: List<DataType>
init {
viewModelScope.launch {
dataLoader()
}
doSomething(loadedData[0])
}
suspend fun dataLoader(){
dataSource.getData().collect {
loadedData = it
}
}
fun doSomething(loadedData: List<DataType>){
_state.value = _state.value.copy(thing = newValueFromLoadedData[0])
}
}
and obviously loadedData is not initialized.
Also, please let me know if this not the right way of doing what I want to do...