kotlin 在单独的模块导航图中创建sharedViewModel(Compose)

xxls0lw8  于 2023-05-29  发布在  Kotlin
关注(0)|答案(1)|浏览(186)

我试图创建一个共享视图模型的示例(使用hilt),在我的2个可组合的“屏幕”之间共享,它们都在一个单独的图中(由于嵌套导航),我无法找到一种方法来创建视图模型(并且在其他模块中创建示例似乎...错得离谱)
代码:
主活动中的主导航

Surface(
    modifier = Modifier.fillMaxSize(),
    color = MaterialTheme.colors.background
) {
    // I technically could create the viewModel instance here, but that seems awful!
    val mainNavController = rememberNavController()
    NavHost(
        navController = mainNavController,
        startDestination = ProductRoutes.ProductGraph.route
    ) {
        productGraph(navController = mainNavController)
    }
}

产品图表:

fun NavGraphBuilder.productGraph(
    navController: NavController
) {
    navigation(
        startDestination = ProductRoutes.ProductListScreen.route,
        route = ProductRoutes.ProductGraph.route
    ) {
        composable(route = ProductRoutes.ProductListScreen.route) {
            ProductListScreen(navController = navController)
        }

        composable(
            route = ProductRoutes.ProductDetailScreen.route
        ) {
            ProductDetailScreen(navController = navController)
        }
        // both need the same view model to pass a product to display (from the list to detail screen)
    }
}

我正在寻找在这种情况下以合理的方式创建VM的方法
任何提示/提示/ gists将不胜感激,谢谢:)

6ovsh4lw

6ovsh4lw1#

我认为我们可以使用navBackEntry从中获取视图模型,只有在导航到另一个时不弹出之前的navGraph时才能工作。

navigation(
        startDestination = ProductRoutes.ProductListScreen.route,
        route = ProductRoutes.ProductGraph.route
    ) {

        composable(route = ProductRoutes.ProductListScreen.route) {
            val parentEntry = remember {
        navController.getBackstackEntry("the route to your previous nav 
                graph")
          }
          val vm = viewModel<ViewModelClass>(parentEntry)
            ProductListScreen(navController = navController)
        }

        composable(
            route = ProductRoutes.ProductDetailScreen.route
        ) {
            ProductDetailScreen(navController = navController)
        }
        // both need the same view model to pass a product to display (from the list to detail screen)
    }

相关问题