android 在函数返回值之前无法从firebase恢复数据

mhd8tkvw  于 2022-12-31  发布在  Android
关注(0)|答案(1)|浏览(132)

(安卓系统、Kotlin)
我尝试通过存储库从firebase恢复数据,它正在正确地发生,但在错误的时间

override suspend fun getAllOnline(): MutableStateFlow<ResourceState<List<DocModel>>> {
    val docList: MutableList<DocModel> = mutableListOf()
    auth = FirebaseAuth.getInstance()
    database
        .child(auth.currentUser!!.uid)
        .addValueEventListener(object: ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                for(docs in snapshot.children) {
                    val doc = docs.getValue(DocModel::class.java)
                    docList.add(doc!!)
                }
            }

            override fun onCancelled(error: DatabaseError) {
                return
            }
        })
    return if(docList.isNullOrEmpty()) {
        MutableStateFlow(ResourceState.Empty())
    } else {
        MutableStateFlow(ResourceState.Success(docList))
    }
}

问题是:我的单据列表是在返回完成后填充的。我调试并记录了它,结果总是在函数结束后出现,所以它不返回数据。需要设法只在数据检索完成后才允许返回。
有什么建议吗?
先谢了

bfnvny8b

bfnvny8b1#

你可以使用await,或者如果你希望代码保持这种方式,你也可以使用suspendCoroutine,如下所示:

private suspend fun getFirebaseToken(): String? {
    return try {
        val suspendCoroutine = suspendCoroutine<Task<String>> { continuation ->
            FirebaseMessaging.getInstance().token.addOnCompleteListener {
                continuation.resume(it)
            }
        }
        if (suspendCoroutine.isSuccessful && suspendCoroutine.result != null)
            suspendCoroutine.result
        else null
    } catch (e: Exception) {
        e logAll TAG
        null
    }
}

suspendCoroutine可以替换为suspendCoroutine
并且您将在“continuation.resume(docList)”中传递docList,而不是“it”:
最终代码如下所示:

override suspend fun getAllOnline(): MutableStateFlow<ResourceState<List<DocModel>>> {

auth = FirebaseAuth.getInstance()

val docList = suspendCoroutine<MutableList<DocModel>>{ continuation->
  database
    .child(auth.currentUser!!.uid)
    .addValueEventListener(object: ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            val docList: MutableList<DocModel> = mutableListOf()
            for(docs in snapshot.children) {
                val doc = docs.getValue(DocModel::class.java)
                docList.add(doc!!)
            }
            continuation.resume(docList)
        }

        override fun onCancelled(error: DatabaseError) {
            continuation.resume(emptyList<DocModel>())
        }
    })
}
return if(docList.isSuccessful && docList.result != null && 
       docList.result.isNullOrEmpty()) {
    MutableStateFlow(ResourceState.Success(docList.result))
} else {
    MutableStateFlow(ResourceState.Empty())
}

}

相关问题