How to initialize a field in view model if I need to call the suspend function to get the value?
I a have suspend function that returns value from a database.
suspend fun fetchProduct(): Product
When I create the view model I have to get product in this field
private val selectedProduct: Product
I tried doing it this way but it doesn't work because I'm calling this method outside of the coroutines
private val selectedProduct: Product = repository.fetchProduct()
CodePudding user response:
You need to run the function inside a coroutine scope to get the value.
if you're in a ViewModel() class you can safely use the viewModelScope
private lateinit var selectedProduct:Product
fun initialize(){
viewModelScope.launch {
selectedProduct = repository.fetchProduct()
}
}
CodePudding user response:
Since fetchProduct()
is a suspend function, you have to invoke it inside a coroutine scope.
For you case I would suggest the following options:
- Define
selectedProduct
as nullable and initialize it inside yourViewModel
asnull
:
class AnyViewModel : ViewModel {
private val selectedProduct: Product? = null
init {
viewModelScope.launch {
selectedProduct = repository.fetchProduct()
}
}
}
- Define selectedProduct as a
lateinit var
and do the same as above;
Personally I prefer the first cause I feel I have more control over the fact that the variable is defined or not.