[英]Observing LiveData in JetPack Composable
我正在使用宠物应用程序练习 JetPack Compose,我正在尝试通过 LiveData 在启动画面中观察加载 state。 但是,在我的可组合物中,我被要求提供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()
扩展 function 将LiveData
转换为State
。 此外,与其将LiveData
作为参数传递给 compose,不如先将其转换为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")
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.