android - 在 JetPack Composable 中观察 LiveData

标签 android kotlin android-jetpack-compose

我正在使用宠物应用程序练习 JetPack Compose,并尝试通过 LiveData 观察启动屏幕中的加载状态。但是,在我的可组合项中,我被要求提供 viewLifecycleOwner ,这在可组合项中似乎是不可能的。或者我需要将它从 MainActivity 传递下来吗?看起来很笨重,还有其他更 Jetpacky 的方式吗?

@Composable
fun SplashScreen(navController: NavHostController, isLoadingInit: LiveData<Boolean>) {
    val scale = remember {
        Animatable(0f)
    }
    
    LaunchedEffect(key1 = true) {
        scale.animateTo(
            targetValue = 0.5f,
            animationSpec = tween(
                durationMillis = 500,
                easing = {
                    OvershootInterpolator(2f).getInterpolation(it)
                }
            )
        )
    }

    Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
        Image(
            painter = painterResource(id = R.drawable.pokeball),
            contentDescription = "Pokemon Splashscreen",
            modifier = Modifier.scale(scale.value)
        )
    }

    isLoadingInit.observe(**viewLifecycleOwner**) {
        navController.navigate("main-screen")
    }
}

最佳答案

您可以使用 LiveData.observeAsState() 扩展函数将 LiveData 转换为 State。另外,不要将 LiveData 作为参数传递来进行组合,而是先将其转换为 State,然后将其作为参数传递。

// This is probably what you are doing right now (inside a NavGraph)
val isLoadingInit = viewModel.isLoadingInit
SplashScreen(navController, isLoadingInit)

将其更改为:

val isLoadingInit by viewModel.isLoadingInit.observeAsState()
SplashScreen(navController, isLoadingInit)

然后,

@Composable
fun SplashScreen(navController: NavHostController, isLoadingInit: Boolean) {
    LaunchedEffect(isLoadingInit) {
        if(!isLoadingInit) // Or maybe its negation
            navController.navigate("main-screen")
    }
    ...
}

关于android - 在 JetPack Composable 中观察 LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70225765/

相关文章:

Android ActionBarSherlock - 如何更改 API <3.0 的主题以及 API >=3.0 的主题

android - RecyclerView 使用 Room 和 PagingListAdapter 向下滚动数据更新

android - Android 中的音频编辑

android - 如何在行内排列元素,其中一个元素具有无限宽度?

android - Jetpack Compose TextField 是否存在辅助文本、错误消息、字符计数器?

android - ClassNotFoundException : android. view.OnBackInvokedCallback with Compose 1.2.0-alpha07

java - 为什么 javamail API 有一个消息发件人数组?

android - Firebase订单通过时间戳实际未订购

algorithm - BST 层序遍历的惯用 Kotlin

Kotlin 为什么尽管进行空检查仍需要非空断言