gpt4 book ai didi

android - 在函数之间传递 MutableLiveData

转载 作者:行者123 更新时间:2023-12-02 12:31:02 28 4
gpt4 key购买 nike

我在 ViewModel 中有一个函数“A”,它从 firebase 检索数据,并将该值分配给 MutableLiveData<Int> (所有这些都包含在 onSuccessListener 中)并返回。此函数是从同一 ViewModel 中的另一个函数“B”调用的。但是当我尝试返回 MutableLiveData<Int> 时从“A”开始,它返回为 0(默认值)。但是如果我为 MutableLiveData<Int> 赋值在 onSuccessListener 之外,则返回值。

代码:

val num = MutableLiveData<Int>().default(0)

private fun A():Int {
FirebaseOperation
.addOnSuccessListener{ //it:DocumentSnapshot!
num.value = it.num
}
return num.value.toInt() // outside onsuccesslistener, default value 0 is being returned
}

private fun B() {
val num2 = A()
}

更新:在了解了 firebase 回调 hell 之后,我已经切换到 firebase 的 kotlin 协程(实现 org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.1.1 作为依赖项)更新代码:

private suspend fun A():DocumentSnapshot? {
return Firebase.firestore.collection("collection").documet("document").get().await()
}

private suspend fun B(): Int{
val data = A()
val user = data.toObject<User>()
val num = user.num
return num
}

但是主线程卡住并且应用程序崩溃并显示 Reason: Input dispatching timed out (Waiting to send key event because the focused window has not finished processing all of the input events that were previously delivered to it. Outbound queue length: 0. Wait queue length: 9.)

最佳答案

如果您使用 kotlinx.coroutines , 你可以使用 suspendCoroutine .

private suspend fun A(): Int = suspendCoroutine { cont ->
FirebaseOperation.addOnSuccessListener{ // it: DocumentSnapshot!
cont.resume(it.num)
}
}

private suspend fun B() {
val num2 = A()
}

关于android - 在函数之间传递 MutableLiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62254528/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com