【问题标题】:Why does Kotlin skip this section of code in a firestore call? [duplicate]为什么 Kotlin 在 firestore 调用中跳过这部分代码? [复制]
【发布时间】:2021-03-11 07:36:32
【问题描述】:

我有此代码来检查用户是否已存在于 firestore 中

1  private fun usernameRepeated(db: FirebaseFirestore, username: String): Boolean {
2      var res = false
3      db.collection("User").whereEqualTo("username", username).get().addOnSuccessListener { task ->
4          res = task.documents.isNotEmpty()
5      }
6      return res
7  }

但它不起作用。我已经调试了在第 2 行、第 4 行和第 6 行设置断点的代码。当调试器到达这一点时,它会正确运行第 2 行和第 3 行,但会跳过第 4 行并直接转到第 6 行,始终返回“false”。在我调用这个函数的其余行运行很久之后,它返回并只运行第 4 行,此时已经太晚了。

【问题讨论】:

    标签: android firebase kotlin


    【解决方案1】:

    它不会跳过该部分,而是仅在检索到数据库结果时异步执行。

    发生的情况是该方法返回 False,然后才执行回调。

    你应该传递一个回调而不是返回结果

    private fun usernameRepeated(db: FirebaseFirestore, username: String, onSuccess: (result: Task) => Boolean): Boolean {
     db.collection("User").whereEqualTo("username", username).get().addOnSuccessListener { onSuccess }
    }
    

    或者您可以使用协程、RxJava 或其他 API 阻止请求

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2013-08-22
      • 2014-10-21
      • 2011-09-11
      • 1970-01-01
      • 2020-09-26
      相关资源
      最近更新 更多