是否有任何方法为Fi还原文档实现ChildEventListener (即当字段被添加/移除到文档中时,必须触发只获取添加/删除字段快照的侦听器)。最好,它必须具有OnChildAdded、OnChildChanged和OnChildDeleted功能,类似于Firebase实时数据库。
另外,是否有任何方法可以让多个用户一次不发生冲突地操作单个Firestore文档?(例如,用户1、2和3同时将其名称添加到同一文档中)。您能在Android中提供这方面的实现吗?
发布于 2018-06-16 09:54:02
这是如何在FireStore中这样做的,您需要使用添加的、修改的、删除的枚举。
//Listener
update_listener = mDatabase.collection("Announcements").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
//If something went wrong
if (e != null)
Log.w(TAG, "ERROR : ", e);
if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
//Instead of simply using the entire query snapshot
//See the actual changes to query results between query snapshots (added, removed, and modified)
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
switch (doc.getType()) {
case ADDED:
if (!isFirstListLoaded){
//Call the model to populate it with document
AnnouncementModel annonPost = doc.getDocument().toObject(AnnouncementModel.class)
.withId(doc.getDocument().getId());
//This will be called only if user added some new post
announcementList.add(0, annonPost);
announcementRecyclerAdapter.notifyItemInserted(0);
//Notify the adapter to update all position
announcementRecyclerAdapter.notifyItemRangeChanged(0, announcementList.size());
Log.d(TAG,"THIS SHOULD BE CALLED");
/* //Just call this method once
if (noContent.isShown()){
//This will be called only if user added some new post
announcementList.add(annonPost);
announcementRecyclerAdapter.notifyDataSetChanged();
noContent.setVisibility(View.GONE);
label.setVisibility(View.VISIBLE);
}*/
}
break;
case MODIFIED:
break;
case REMOVED:
//Get the document ID of post in FireStore
//Perform a loop and scan the list of announcement to target the correct index
for (int i = 0; i < announcementList.size(); i++) {
//Check if the deleted document ID is equal or exist in the list of announcement
if (doc.getDocument().getId().equals(announcementList.get(i).AnnouncementsID)) {
//If yes then delete that object in list by targeting its index
Log.d(TAG, "Removed Post: " + announcementList.get(i).getTitle());
announcementList.remove(i);
//Notify the adapter that some item gets remove
announcementRecyclerAdapter.notifyItemRemoved(i);
//Notify the adapter to update all position
announcementRecyclerAdapter.notifyItemRangeChanged(i, announcementList.size());
break;
}
}
break;
}
}
isFirstListLoaded = false;
}
}
});https://stackoverflow.com/questions/46689970
复制相似问题