如何等待 Firestore 完成然后返回布尔结果?

时间:2021-04-23 15:26:13

标签: android kotlin google-cloud-firestore

我想在集合中的文档是否存在时返回 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;
    }

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

1 个答案:

答案 0 :(得分:1)

您在 get 调用完成之前返回结果。不要忘记这是异步的。

尝试使用 async 和 await 而不是完整的侦听器。