我正在使用宠物应用程序练习 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/