【问题标题】:How do I wait until query is completed in kotlin? [duplicate]如何等到在 kotlin 中完成查询? [复制]
【发布时间】:2019-11-23 07:02:00
【问题描述】:

如果查询成功但 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
    }

【问题讨论】:

    标签: android firebase kotlin synchronization blocking


    【解决方案1】:

    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
    }
    

    【讨论】:

    • 谢谢!编译器要求我有一个类型,所以我添加了 Unit 并且它工作私有 fun checkDidAdd(geoPoint: GeoPoint, fullAddress: String, onResult: (Boolean) -> (Unit)):Boolean {
    • 好主意。谢谢
    猜你喜欢
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2016-11-19
    相关资源
    最近更新 更多