Last active
April 23, 2024 13:29
-
-
Save tfcporciuncula/886e511770a25d79d5a7a3d4449c0847 to your computer and use it in GitHub Desktop.
Getting arg from ViewModel with savedStateHandle
This file contains 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
// Both screens look the same, but now we have a ViewModel and some differences on the App composable | |
@HiltViewModel | |
class DetailsViewModel @Inject constructor( | |
savedStateHandle: SavedStateHandle, | |
) : ViewModel() { | |
private val state = MutableStateFlow(requireNotNull(savedStateHandle.get("arg"))) | |
fun state() = state.asStateFlow() | |
} | |
@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") }, | |
) | |
} | |
// ---> interesting changes are here <--- | |
composable(route = "details/{arg}") { navBackStackEntry -> | |
val arg = requireNotNull(navBackStackEntry.arguments?.getString("arg")) | |
navBackStackEntry.savedStateHandle.set("arg", arg) | |
val viewModel = hiltViewModel<DetailsViewModel>() | |
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