簡體   English   中英

在 JetPack Composable 中觀察 LiveData

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM