Tim Malseed
03/19/2021, 12:39 AMViewModel
as a state container for a Composable screen. The ViewModel
is scoped to the nav graph via @HiltViewModel
& `hiltNavGraphViewModel()`` . It seems that this pattern does not support assisted injection into the ViewModel
, so I have to pass initial state to the screen's Compose function, and then pass that state into the ViewModel
. This feels a bit uncomfortable. Am I approaching this the wrong way?Tim Malseed
03/19/2021, 12:39 AMExerciseScreen(
viewModel = hiltNavGraphViewModel(),
routine = previousArguments.getParcelable(ARG_ROUTINE)
...
@Composable
fun ExerciseScreen(
viewModel: ExerciseScreenViewModel,
routine: Routine,
) {
val routine: Routine by viewModel.getRoutine(routine).collectAsState(initial = routine)
...
@HiltViewModel
class ExerciseScreenViewModel @Inject constructor(
private val appRepository: AppRepository,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
fun getRoutine(routine: Routine): Flow<Routine> {
return appRepository.getRoutines(listOf(routine.id)).map { routines -> routines.first() }
}
...
Tim Malseed
03/19/2021, 12:41 AMIan Lake
03/19/2021, 1:28 AMIan Lake
03/19/2021, 1:30 AMTim Malseed
03/19/2021, 2:19 AMTim Malseed
03/19/2021, 3:18 AMyour app repository should always be the source of truth (using stateIn to save the last value)Can you expound on that last point? I'm not sure why stateIn would be required - as the AppRepository would be persist and retrieve the latest value anyway..
Ian Lake
03/19/2021, 3:57 AMFlow
, but not from a StateFlow
). If your ViewModel uses stateIn
, then after a configuration change or when you return to that destination in Navigation Compose, your ViewModel already has the state immediately available for that first compositionTim Malseed
03/19/2021, 4:48 AM