Created
April 23, 2024 13:31
-
-
Save tfcporciuncula/1bd7422e83f26ede06e46a8fc1a16af6 to your computer and use it in GitHub Desktop.
Getting arg from ViewModel with Hilt assisted injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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