如何确保无论活动的生命周期如何,Firebase 数据库的更新过程都已完成



我的应用有一个显示新闻文章的活动,它有一个书签 ImageButton。单击时,将调用如下所示的方法

public void onBookmarkClick(View view){
if (isBookmarked){
bookmarkedDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Article articleValue = snapshot.getValue(Article.class);
String id = snapshot.getKey();
if (article.equals(articleValue)){
bookmarkedDatabase.child(id).removeValue();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}else {
String id = bookmarkedDatabase.push().getKey();
bookmarkedDatabase.child(id).setValue(article);
}
isBookmarked = !isBookmarked;
setupBookmarkIcon();
}

但是当我在单击书签按钮后立即旋转屏幕或按后退按钮时,文章不会添加到书签中。

如何确保从/向 Firebase 数据库读取和写入的过程已完成,即使活动被销毁也是如此。

您可以使用完整的侦听器来了解更新是否成功。来自火力基地文档

Add a Completion Callback
If you want to know when your data has been committed, you can add a completion listener. 
Both setValue() and updateChildren() take an optional completion 
listener that is called when 
the write has been successfully committed to the database. 
If the call was unsuccessful, the listener is passed an error object indicating why the failure occurred

火力基地

或者我的建议是使用 viewModel 类并从那里进行更新。

视图模型

最新更新