Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Created April 23, 2024 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfcporciuncula/1bd7422e83f26ede06e46a8fc1a16af6 to your computer and use it in GitHub Desktop.
Save tfcporciuncula/1bd7422e83f26ede06e46a8fc1a16af6 to your computer and use it in GitHub Desktop.
Getting arg from ViewModel with Hilt assisted injection
@HiltViewModel(assistedFactory = DetailsViewModel.Factory::class)
class DetailsViewModel @AssistedInject constructor(
@Assisted val arg: String,
) : ViewModel() {
@AssistedFactory interface Factory {
fun create(arg: String): DetailsViewModel
}
private val state = MutableStateFlow(DetailsUiState(arg = arg))
fun state() = state.asStateFlow()
}
data class DetailsUiState(val arg: String)
@Composable
fun App(
modifier: Modifier = Modifier,
) {
Box(
modifier = modifier
.fillMaxSize()
.background(color = colorScheme.background),
) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "start") {
composable(route = "start") {
StartScreen(
onNavigateClick = { arg -> navController.navigate(route = "details/$arg") },
)
}
composable(route = "details/{arg}") { navBackStackEntry ->
val arg = requireNotNull(navBackStackEntry.arguments?.getString("arg"))
val viewModel = hiltViewModel<DetailsViewModel, DetailsViewModel.Factory>(
creationCallback = { factory -> factory.create(arg = arg) },
)
val state by viewModel.state().collectAsStateWithLifecycle(lifecycleOwner = navBackStackEntry)
DetailsScreen(arg = state.arg)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment