我只查询Firestore集合上的新文档:
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
CollectionReference collectionReference = firestore.collection("my_data");
EventListener<QuerySnapshot> eventListener = (snapshots, e) -> {
if (e != null || snapshots == null) {
return;
}
for (DocumentChange dc : snapshots.getDocumentChanges()) {
if (dc == null) {
continue;
}
switch (dc.getType()) {
case ADDED:
onDocumentAdded(dc.getDocument());
break;
case MODIFIED:
onDocumentModified(dc.getDocument());
break;
case REMOVED:
onDocumentRemoved(dc.getDocument());
break;
}
}
// Last event call time
SharedPreferences prefs = App.getInstance().getSharedPreferences("firestore", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("last_event_call_time", new Date().getTime());
editor.apply();
};
我有一个方法负责注册监听器:
/**
* Register the event listener to query new documents, updates and removes only from the last event call time
*/
public void registerListener(ThreadTaskExecutor executor) {
if (listenerRegistration != null) {
return;
}
SharedPreferences prefs = MyApplication.getInstance().getSharedPreferences("firestore", Context.MODE_PRIVATE);
Date time = new Date(prefs.getLong("last_event_call_time", new Date().getTime()));
listenerRegistration = collectionReference
.orderBy("timestamp")
.startAt(new Timestamp(time))
.addSnapshotListener(executor, eventListener);
}
/**
* Removes the event listener
*/
public void removeListener() {
if (listenerRegistration == null) {
return;
}
listenerRegistration.remove();
listenerRegistration = null;
}
public void add(String documentId, Map<String, Object> data) throws Exception {
data.put("timestamp", FieldValue.serverTimestamp());
Tasks.await(collectionReference.document(documentId).set(data));
}
public void update(String documentId, Map<String, Object> data) throws Exception {
data.put("timestamp", FieldValue.serverTimestamp());
Tasks.await(collectionReference.document(documentId).update(data));
}
public void delete(String documentId) throws Exception {
delete(collectionReference.document(documentId));
}
public void delete(DocumentReference docRef) throws Exception {
Tasks.await(docRef.delete());
}
public static class ThreadTaskExecutor implements Executor {
@Override
public synchronized void execute(Runnable command) {
new Thread(command).start();
}
}
我在两个设备中打开应用程序,事件侦听器已注册。
当我更新设备A上的内容时,设备B也会收到通知(很好)。
当我删除设备A上的某些内容时,设备B也会收到通知(awsome)。
然而。。。
如果我在设备A上创建了一些东西,打开设备B上的应用程序(listener registered),添加的事件就会被传递。
如果我在设备A上更新了一些东西,打开设备B上的应用程序(注册了侦听器),添加的事件也会被传递(很奇怪,但我可以解决它)。
问题是:
你知道吗?