gpt4 book ai didi

android - 如何等到在 kotlin 中完成查询?

转载 作者:行者123 更新时间:2023-12-02 13:20:37 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to return a list from Firestore database as a result of a function in Kotlin?

(3 个回答)


2年前关闭。




如果查询成功但 kotlin 是异步的,我正在尝试返回一个 bool 值。

private fun checkDidAdd(geoPoint: GeoPoint, fullAddress: String):Boolean {
var added = false
scope.launch {
val docRef = db.collection("listings")
.get()
.addOnSuccessListener { result ->
for (document in result) {
//todo
}
added = true
}



}.addOnFailureListener { exception ->
Log.d("TAG", "Error getting documents: ", exception)
}
println("done!!")
}

return added
}

最佳答案

Kotlin本身不是异步的。但是,您的函数是异步的,因此您不能只返回 Boolean .实现这一点的一种方法是创建一个接口(interface)。例如:

interface ResultListener {
fun onResult(isAdded: Boolean)
fun onError(error: Throwable)
}

并将其传递给您的函数:
private fun checkDidAdd(geoPoint: GeoPoint, fullAddress: String, resultListener: ResultListener) {
var added = false
scope.launch {
val docRef = db.collection("listings")
.get()
.addOnSuccessListener { result ->
for (document in result) {
//todo
}
resultListener.onResult(true)
}



}.addOnFailureListener { exception ->
resultListener.onError(exception)
}
println("done!!")
}

return added
}

如果您不想使用接口(interface)并且不关心错误,并且由于您使用的是 kotlin,您可以执行以下操作:
private fun checkDidAdd(geoPoint: GeoPoint, fullAddress: String, onResult: (Boolean) -> ()):Boolean {
var added = false
scope.launch {
val docRef = db.collection("listings")
.get()
.addOnSuccessListener { result ->
for (document in result) {
//todo
}
onResult(true)
}



}.addOnFailureListener { exception ->
Log.d("TAG", "Error getting documents: ", exception)
}
println("done!!")
}

return added
}

关于android - 如何等到在 kotlin 中完成查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57025120/

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