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.
Code:
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()
}
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
}
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.)