如何等待直到在Kotlin中完成查询?

时间:2019-07-14 06:32:13

标签: android firebase kotlin synchronization blocking

如果查询成功但Kotlin是异步的,我试图返回一个布尔值。

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
    }

1 个答案:

答案 0 :(得分:0)

Kotlin本身不是异步的。但是,您的函数是异步的,因此您不能仅返回Boolean。实现此目的的一种方法是创建一个接口。例如:

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
}

如果您不想使用接口并且不关心错误,并且由于使用的是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
}