【问题标题】:How can i wait until the onsuccess listener has a result in Kotlin我怎样才能等到 onsuccess 侦听器在 Kotlin 中有结果
【发布时间】:2021-04-06 16:25:10
【问题描述】:

我有这个代码

val collectionDb = db.collection(collection)
                .add(user4)
                .addOnSuccessListener { documentReference ->
                    Log.d("SUCCESS", "DocumentSnapshot added with ID: ${documentReference.id}")
                    println(documentReference.id)
                }
                .addOnFailureListener { e ->
                    Log.w("FAIL", "Error adding document", e)
                }

                //here wait

                println("more code")

    }

输出首先是more code,然后是DocumentReference.id

但我希望在 //here wait 上脚本暂停,直到成功或失败。

我是新手,如果你能帮助我,那就太好了。

【问题讨论】:

  • 你也可以看看这个answer

标签: android database firebase kotlin


【解决方案1】:

但我希望在 //这里等待脚本暂停,直到出现 成功或失败。

那是不可能的。这就是异步操作的重点——无论成功还是失败,它都会在稍后的某个时间点完成,而那个时间是什么时候,我们真的无法确定。如果您想了解有关如何处理这些类型的函数的更多信息,我在这里有一个问答: Why does my function that calls an API return an empty or null value?

但最好的办法是在 addOnSuccessListener 侦听器中添加所有相关代码,因为这是您知道请求已完成且成功的地方

【讨论】:

    【解决方案2】:

    当您想在成功或失败后执行脚本时,只需创建一个方法并从成功或失败回调中调用它,如下所示。请检查以下是否有用。

     val collectionDb = db.collection(collection)
                .add(user4)
                .addOnSuccessListener { documentReference ->
                    Log.d("SUCCESS", "DocumentSnapshot added with ID: ${documentReference.id}")
                    println(documentReference.id)
                    doRequiredOperation("Success")
                }
                .addOnFailureListener { e ->
                    Log.w("FAIL", "Error adding document", e)
                    doRequiredOperation("failuire")
                }
    
    
    fun doRequiredOperation(msg:String){
        if(msg.equals("Success"){
            println("more code"). //It will execute after success callback 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 2016-05-19
      • 2015-03-26
      • 1970-01-01
      相关资源
      最近更新 更多