如何在 Compose NavGraph 内的两个或多个 Jetpack 可组合之间共享视图模型? [英] How to share a viewmodel between two or more Jetpack composables inside a Compose NavGraph?

查看:77
本文介绍了如何在 Compose NavGraph 内的两个或多个 Jetpack 可组合之间共享视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子.

对于身份验证,我们将使用 2 个屏幕 - 一个屏幕输入电话号码,另一个屏幕输入 OTP.

For authentication, we'll be using 2 screens - one screen to enter phone number and the other to enter OTP.

这两个屏幕都是在 Jetpack Compose 中制作的,对于 NavGraph,我们使用的是撰写导航.

Both these screens were made in Jetpack Compose and the for the NavGraph, we are using compose navigation.

另外我不得不提到 DI 是由 Koin 处理的.

Also I have to mention that DI is being handled by Koin.

val navController = rememberNavController()

NavHost(navController) {
    navigation(
        startDestination = "phone_number_screen",
        route = "auth"
    ) {
        composable(route = "phone_number_screen") {
            // Get's a new instance of AuthViewModel
            PhoneNumberScreen(viewModel = getViewModel<AuthViewModel>())
        }

        composable(route = "otp_screen") {
            // Get's a new instance of AuthViewModel
            OTPScreen(viewModel = getViewModel<AuthViewModel>())
        }
    }
}

那么我们如何在 Jetpack compose NavGraph 中的两个或多个可组合项之间共享相同的视图模型?

So how can we share the same viewmodel among two or more composables in a Jetpack compose NavGraph?

推荐答案

使用 Hilt,您可以执行以下操作.但是因为你用的是Koin,我还不知道Koin的方式.

Using Hilt you could do something like the below. But since you are using Koin I don't know the way of Koin yet.

@Composable
fun MyApp() {
    NavHost(navController, startDestination = startRoute) {
        navigation(startDestination = innerStartRoute, route = "Parent") {
            // ...
            composable("exampleWithRoute") { backStackEntry ->
                val parentEntry = remember {
                  navController.getBackStackEntry("Parent")
                }
                val parentViewModel = hiltViewModel<ParentViewModel>(
                  parentEntry
                )
                ExampleWithRouteScreen(parentViewModel)
            }
        }
    }
}

官方文档:https://developer.android.com/jetpack/compose/图书馆#hilt

这篇关于如何在 Compose NavGraph 内的两个或多个 Jetpack 可组合之间共享视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆