【发布时间】:2020-09-26 23:21:41
【问题描述】:
我在 ViewModel 中有一个函数“A”,它从 firebase 检索数据,并将值分配给 MutableLiveData<Int>(所有这些都包含在 onSuccessListener 中)并返回它。此函数是从同一 ViewModel 中的另一个函数“B”调用的。但是当我尝试从'A'返回MutableLiveData<Int>时,它返回为0(默认值)。但是,如果我在 onSuccessListener 之外为 MutableLiveData<Int> 赋值,则返回该值。
代码:
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回调地狱之后,我已经切换到了用于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.) 而崩溃
【问题讨论】:
标签: android firebase kotlin google-cloud-firestore kotlin-coroutines