【问题标题】:How to wait Firestore completed and then return boolean result? [duplicate]如何等待 Firestore 完成然后返回布尔结果? [复制]
【发布时间】:2021-07-17 19:49:42
【问题描述】:

当集合中的文档存在与否时,我想返回 True 或 False。但它总是返回 false。

if (checkItemDeleted(post)) {
   // true, item still there
} else {
  // false, item deleted
}
boolean result = false;
private boolean checkItemDeleted(Post post) {
        mPostsCollection
                .document(post.itemID)
                .get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()){
                        if (task.getResult().exists()) {
                            // document exists
                            result = true;
                        } else {
                            // document not exists
                            result = false;
                        }
                    }
                });
        return result;
    }

我还在学习中,谢谢你的帮助。

【问题讨论】:

  • 您不能等待异步加载的数据。需要数据的代码需要在完成监听器中,或者从那里调用,或者使用 Kotlin 的await

标签: android kotlin google-cloud-firestore


【解决方案1】:

您在 get 调用完成之前返回结果。别忘了那是异步的。

尝试使用 async 和 await 代替完整的侦听器。

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多