Hello.
Can anybody show me how to create a viewmodel that have a function for finding an element using the id returning a flow?
Ive been struggling with this topic, but when executing the app it doesnt return data :(
not kotlin but kotlin colored 3
c
Christian Ricardo
08/18/2023, 4:14 AM
hi @marlonlom! 😄
can you share the code?
why would you need a flow for that? 🤔
m
marlonlom
08/19/2023, 11:37 PM
@Christian Ricardo
The Code:
Copy code
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class CatalogDetailViewModel(
private val repository: CatalogDetailRepository
) : ViewModel() {
fun find(itemId: Long) = repository.find(itemId)
companion object {
fun factory(
repository: CatalogDetailRepository
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return CatalogDetailViewModel(repository) as T
}
}
}
}
marlonlom
08/19/2023, 11:38 PM
The flow is for the ui state handling...
c
Christian Ricardo
08/21/2023, 4:37 AM
yeah, but, I mean what would be the use case?
for example, you click an item in the catalog
the view inform that event to the ViewModel and the ViewModel call a Use Case, Action, repository or whatever... and update a MutableState property witch the View is listening
I think it's easiest, the view shouldn't execute logic
if you want a flow, for example for a list of messages you need a MutableStateFlow
m
marlonlom
08/29/2023, 4:01 AM
Yeah, you said it. In my case, its to find a catalog element with additional information. I did use a mutablestateflow, but, in repository ( i did think about usecases, but more classes, more complex -imho- ) the finding/query process builds the detailed info.
I did use a state variable in viewmodel, the thing is: check that while recomposition, handle the case when state its changing/rebuilding 👍🏼