使用ViewModel和LiveData来解决该问题。在Activity或Fragment中创建ViewModel并使用LiveData来观察数据的变化。这样即使屏幕旋转或者配置变化导致Activity或Fragment重新创建,ViewModel也会持有旧有的数据并且LiveData仍可以接收到从Firestore返回的新数据。
示例代码如下:
public class MyViewModel extends ViewModel {
private final LiveData> myDataList;
private final MyRepository myRepository = new MyRepository();
public MyViewModel() {
myDataList = myRepository.getMyDataList();
}
public LiveData> getMyDataList() {
return myDataList;
}
}
public class MyRepository {
private final MutableLiveData> myDataList = new MutableLiveData<>();
public MyRepository() {
FirebaseFirestore.getInstance().collection("myCollection")
.addSnapshotListener((queryDocumentSnapshots, e) -> {
if (e != null) {
Log.e(TAG, "Firestore listener failed", e);
return;
}
List dataList = new ArrayList<>();
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
dataList.add(documentSnapshot.toObject(MyData.class));
}
myDataList.postValue(dataList);
});
}
public LiveData> getMyDataList() {
return myDataList;
}
}
public class MyActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
viewModel.getMyDataList().observe(this, myDataList -> {
// 处理数据变化
});
}
}