【发布时间】:2020-01-23 08:33:44
【问题描述】:
我是 Android 后台任务的新手。我正在使用 Firestore 执行以下任务:
-
阅读文档。 https://firebase.google.com/docs/firestore/query-data/get-data
DBInstance.collection("restaurants") .get() .addOnCompleteListener(task -> { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) { // some other code } } else { Log.d(TAG, "Error getting documents: ", task.getException()); } }); -
收听另一个文档的实时更新。 https://firebase.google.com/docs/firestore/query-data/listen
final DocumentReference docRef = DBInstance.collection("users").document(FirebaseAuth.getInstance().getCurrentUser().getUid()); docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) { if (e != null) { Log.w(TAG, "Listen failed.", e); return; } String source = snapshot != null && snapshot.getMetadata().hasPendingWrites() ? "Local" : "Server"; if (snapshot != null && snapshot.exists()) { Log.d(TAG, source + " data: " + snapshot.getData()); // some other code is run } else { Log.i(TAG,"no snapshot found"); } } });
由于这些是异步进程,因此它们是同时执行的(大致)。
我想在 1. 完成和 2. 返回非空快照时触发一个独立的方法。因此,当上面的some other code cmets 已经完成。
所以,我本质上想要一些后台进程处于空闲状态/侦听上述两个条件并执行任务/调用更新某些 UI 功能的方法。
我已经简要了解了BroadcastReciever。这相关吗?或者我可以创建一个在后台线程中运行的自定义侦听器吗?任何建议都会有所帮助,因为我不确定要搜索什么才能找到我想要的。
似乎有效的解决方案(Nehal 部分建议)
这与上面的代码相同,但空白处填写
DBInstance.collection("restaurants")
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
restaurantsLoaded = true;
updateUI();
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
restaurantsLoaded = false;
}
});
final DocumentReference docRef = DBInstance.collection("users").document(FirebaseAuth.getInstance().getCurrentUser().getUid());
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot,
@Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
String source = snapshot != null && snapshot.getMetadata().hasPendingWrites()
? "Local" : "Server";
if (snapshot != null && snapshot.exists()) {
Log.d(TAG, source + " data: " + snapshot.getData());
usersSnapshotTriggered = true;
udpateUI();
} else {
Log.i(TAG,"no snapshot found");
}
}
});
public void updateUI(){
if(usersSnapshotTriggered && restaurantsLoaded){
// perform the updates
}
}
【问题讨论】:
-
你能贴一些代码吗?
-
@NehalGodhasara 添加了我的代码
标签: java android firebase asynchronous google-cloud-firestore