简体   繁体   English

在 JetPack Composable 中观察 LiveData

[英]Observing LiveData in JetPack Composable

I am practicing JetPack Compose with a pet app and I'm trying to observe a loading state in a Splash screen via LiveData.我正在使用宠物应用程序练习 JetPack Compose,我正在尝试通过 LiveData 在启动画面中观察加载 state。 But, inside my composable I am asked to provide viewLifecycleOwner which seems impossible inside a composable.但是,在我的可组合物中,我被要求提供viewLifecycleOwner ,这在可组合物中似乎是不可能的。 Or do I need to pass it down from the MainActivity?还是我需要从 MainActivity 传递它? Seems clunky, is there another, more Jetpacky way?看起来很笨重,还有另一种更 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")
    }
}

You can convert your LiveData to State using LiveData.observeAsState() extension function.您可以使用LiveData.observeAsState()扩展 function 将LiveData转换为State Also instead of passing a LiveData as a parameter to compose, prefer converting it to a State first and then pass that as a parameter.此外,与其将LiveData作为参数传递给 compose,不如先将其转换为State ,然后将其作为参数传递。

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

Change it to:将其更改为:

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

And then,接着,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM