StateFlowcollectAsState没有更新他的值jetpack撰写导航

问题描述 投票:0回答:1

我正在使用jetpack compose制作简单的导航应用程序。我正在使用撰写导航更改屏幕,使用一些简单的条件,但我的

destination
值始终与我初始化的值相同。我不明白为什么这个值总是与
ScreenOne
相同。如果您检查视图模型中的函数
navigateToScreen
,如果条件为真但
destination
值没有改变。

FunAppNavigation

@Composable
fun FunAppNavigation(
    viewModel: FunAppViewModel = koinViewModel(),
    navController: NavHostController = rememberNavController()
) {
    val destination = viewModel.navigationHandler.destination.collectAsState()

    LaunchedEffect(Unit) {
        viewModel.navigateToScreen()
    }

    LaunchedEffect(key1 = destination) {
        navController.navigate(destination.value.route)
    }

     SideEffect {
        println(">> destination Value $destination")
     }

}

FunAppViewModel

class FunAppViewModel(
    val navigationHandler: NavigationHandler,
) : BaseViewModel() {

    fun navigateToScreen() {
        val destination = if (true) {
            DeviceRoutes.ScreenTwo
        } else {
            DeviceRoutes.ScreenOne
        }
        navigationHandler.navigate(destination)
    }
}

导航处理程序

interface NavigationHandler {
    val destination: StateFlow<DeviceRoutes>
    fun navigate(deviceRoutes: DeviceRoutes)
}

导航器

class Navigator : NavigationHandler {
    private val _destination: MutableStateFlow<DeviceRoutes> =
        MutableStateFlow(DeviceRoutes.ScreenOne)

    override val destination: StateFlow<DeviceRoutes> = _destination

    override fun navigate(deviceRoutes: DeviceRoutes) {
        _destination.value = deviceRoutes
    }
}

设备路由

sealed class DeviceRoutes(val route: String) {
    object ScreenOne : DeviceRoutes("ScreenOne")
    object ScreenTwo : DeviceRoutes("ScreenTwo")
}
android kotlin android-jetpack-compose kotlin-flow jetpack-compose-navigation
1个回答
0
投票

我猜你忘了将

.value
放入 LaunchedEffect 的键中。因此,它将比较您的
state
变量的引用(相同),而不是比较您的目的地状态的内容。

尝试这样:

LaunchedEffect(key1 = destination.value) {
    navController.navigate(destination.value.route)
}
© www.soinside.com 2019 - 2024. All rights reserved.