I have this employee list in my composable:
val employeeViewModel: EmployeeViewModel = viewModel()
val employeeState by employeeViewModel.employeeState.collectAsState(ViewResult.Loading)
ALlEmployees(employeeState = employeeState,
onRefresh = {
// TODO: Re-fetch the list
})
And this is my viewModel
var employeeState: StateFlow<ViewResult<List<Employee>>> = fetchEmployeesUseCase().stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = ViewResult.Loading,
)
private set
I am really not sure how can I refetch the employee list. The flow needs to be re-trigerred somehow. Any help is appreciated.
Well, to achieve this let's start by refactoring the viewModel. The way I always handle it is this:
In the viewModel insider the
fetchEmployees()you could set temporary the state asloading, that in case you have some animation or something like that, otherwise you can omit it and directly update the state. Also in my example we get the data from a repository, you can change it to your useCaseAnd on the part of the UI it would be like this:
Also as recommendation when you heard an state from the viewModel, you could check the library that is recommended:
->
collectAsStateWithLifecycle()It only collects values from a Flow or StateFLow in a lifecycle-aware manner, allowing your app to save unneeded app resources. Specially for cases where you use StateFlow
Here I give you a link of reference: https://developer.android.com/jetpack/compose/state?hl=es-419#use-other-types-of-state-in-jetpack-compose