我创建了一个包含聊天功能的应用程序,并使用 Firestore 集合将所有消息存储在其中。
我为用户提供了删除他们帐户的选项,这意味着删除该集合。
我看到没有直接的方法来删除集合,基本上我需要做的是遍历所有文档并删除它们。
我看到给出了一些解决方案,这个链接建议使用 Executor 来执行删除。
private void deleteCollection(final CollectionReference collection, Executor executor) {
Tasks.call(executor, () -> {
int batchSize = 10;
Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);
List<DocumentSnapshot> deleted = deleteQueryBatch(query);
while (deleted.size() >= batchSize) {
DocumentSnapshot last = deleted.get(deleted.size() - 1);
query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);
deleted = deleteQueryBatch(query);
}
return null;
});
}
有人可以解释如何使用该执行器吗?
我找不到我能理解的来源。尝试了以下但似乎没有从我的数据库中删除任何内容,因为我不确定我是否正确执行:
Executor executor = Runnable::run;
db.collection( "Chats" ).whereEqualTo( "ReceiverID", auth.getUid() ).get()
.addOnCompleteListener( task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document != null) {
CollectionReference cr = db.collection( "Chats" ).document( document.getId() ).collection( document.getId() );
deleteCollection(cr, executor);
}
}
}
} );
我还尝试按如下方式使用 Executor:
executor = new Executor() {
@Override
public void execute(Runnable command) {
executor.execute( command );
}
};
但我收到一条错误消息:
java.lang.StackOverflowError: stack size 8MB
所以我很迷茫如何称呼它。
另外,使用此解决方案与仅使用 for 循环并删除每个文档而不使用执行程序之间有什么区别吗?
谢谢