Hello. Can anybody show me how to create a viewmod...
# android
m
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
hi @marlonlom! 😄 can you share the code? why would you need a flow for that? 🤔
m
@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
      }
    }
  }
}
The flow is for the ui state handling...
c
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
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 👍🏼
c
Something like this
Copy code
fun find(itemId: Long) {
        viewModelScope.launch {
            _selectedItem.value = repository.find(itemId)
        }
    }
and the view is observing the
selectedItem
what I mean is that
find
shouldn't return anything