在函数之间传递MutableLiveData [英] Passing MutableLiveData between functions

查看:61
本文介绍了在函数之间传递MutableLiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function 'A' in a ViewModel that retrieves data from firebase and I assign the value to a MutableLiveData<Int> (all of this is wrapped in onSuccessListener)and return it. This function is called from another function 'B' in the same ViewModel. But when I try to return MutableLiveData<Int> from 'A', it is returned as 0 (the default value). But if I assign value for the MutableLiveData<Int> outside the onSuccessListener, then the value is being returned.

代码:

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回调地狱之后,我切换到了Kotlin Coroutine作为Firebase(将 org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.1.1 实现为依赖项)更新的代码:

Update: After learning about the firebase callback hell, I've switched to kotlin coroutine for firebase (implementing org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.1.1 as a dependancy) Updated Code:

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
}

但是主线程死机,应用程序崩溃,原因是原因:输入调度超时(等待发送键事件,因为焦点窗口尚未完成处理先前传递给它的所有输入事件.出站队列长度:0.等待队列长度:9.)

But the main thread freezes and the app crashes with 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 .

If you use kotlinx.coroutines, you can use suspendCoroutine.

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

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

这篇关于在函数之间传递MutableLiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆