
public class NavBackStackEntry
private constructor(
private val context: Context?,
/**
* The destination associated with this entry
*
* @return The destination that is currently visible to users
*/
@set:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public var destination: NavDestination,
private val immutableArgs: Bundle? = null,
private var hostLifecycleState: Lifecycle.State = Lifecycle.State.CREATED,
private val viewModelStoreProvider: NavViewModelStoreProvider? = null,
/**
* The unique ID that serves as the identity of this entry
*
* @return the unique ID of this entry
*/
public val id: String = UUID.randomUUID().toString(),
private val savedState: Bundle? = null
) :
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner
NavHost(
modifier = modifier,
navController = navController,
startDestination = AuthScreen.Auth.route
) {
navigation(
startDestination = MainScreen.Home.route,
route = MainScreen.Main.route
) {
composable(MainScreen.Home.route) {
..
}
composable(MainScreen.MyPage.route) {
..
}
}
}
@Composable
NavHost(
modifier = modifier,
navController = navController,
startDestination = AuthScreen.Auth.route
) {
navigation(
startDestination = MainScreen.Home.route,
route = MainScreen.Main.route
) {
composable(MainScreen.Home.route) {
val viewModel = it.sharedViewModel<HomeViewModel>(navController)
HomeScreen(viewModel)
}
composable(MainScreen.MyPage.route) {
val viewModel = it.sharedViewModel<HomeViewModel>(navController)
DetailScreen(viewModel)
}
}
}
@Composable
inline fun <reified T : ViewModel> NavBackStackEntry.sharedViewModel(navController: NavController): T {
val navGraphRoute = destination.parent?.route ?: return viewModel()
val parentEntry = remember(this) {
navController.getBackStackEntry(navGraphRoute)
}
return viewModel(parentEntry)
}
@Composable
NavHost(
modifier = modifier,
navController = navController,
startDestination = AuthScreen.Auth.route
) {
navigation(
startDestination = MainScreen.Home.route,
route = MainScreen.Main.route
) {
composable(MainScreen.Home.route) {
val parentEntry = remember(it) {
navController.getBackStackEntry(CreatePickDestinations.SEARCH_ROUTE)
}
val viewModel = hiltViewModel<HomeViewModel>(parentEntry)
HomeScreen(viewModel)
}
composable(MainScreen.MyPage.route) {
val parentEntry = remember(it) {
navController.getBackStackEntry(CreatePickDestinations.SEARCH_ROUTE)
}
val viewModel = hiltViewModel<HomeViewModel>(parentEntry)
// parentEntry를 hiltViewModel 함수 파라미터에 사용
DetailScreen(viewModel)
}
}
}


https://dudgus907.tistory.com/91
https://developer.android.com/reference/androidx/navigation/NavBackStackEntry