AndroidViewModel Fragment Recreates On Screen Rotation with firebase

  android, firebase, google-cloud-firestore, mvvm

I am new to mvvm architecture and jetpack navigation. I am trying to get list of blog from firestore in my application. But while screen orientation,It is not maintaining its state. it is creating new call to firebase.

  1. Please help me with this and

  2. Is it not good practice to use mvvm this way. I am not sure whether this is mvvm pattern at all. Thanks

Here is my HomeFragment.java:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    homeViewModel.getLiveBlogData().observe(this,blogList->{
        Log.i("TAG ::::", "onCreate: ");
        blogAdapter =  new BlogAdapter(blogList);
        blogRecycler.setAdapter(blogAdapter);
        blogAdapter.notifyDataSetChanged();
    });

}   

HomeViewModel.java

public class HomeViewModel extends AndroidViewModel {
BlogRepository blogRepository;

public HomeViewModel(@NonNull Application application) {
    super(application);
    blogRepository = new BlogRepository(application);
}

public MutableLiveData<List<Blog>> getLiveBlogData() {
    return blogRepository.getBlogListMutableLiveData();
}

}
BLogRepository.java

public class BlogRepository {
MutableLiveData<List<Blog>> blogListMutableLiveData;
FirebaseFirestore mFirestore;
Application application;

public BlogRepository(Application application) {
    this.blogListMutableLiveData = new MutableLiveData<>();
    mFirestore = FirebaseFirestore.getInstance();
    this.application = application;
}

public MutableLiveData<List<Blog>> getBlogListMutableLiveData() {
    mFirestore.collection("Blog").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
            List<Blog> blogList = new ArrayList<>();
            for (QueryDocumentSnapshot doc : value) {
                if (doc != null) {
                    blogList.add(doc.toObject(Blog.class));
                }
            }
            blogListMutableLiveData.postValue(blogList);
        }
    });
    return blogListMutableLiveData;

}

}
Database structure:
firestore data structure

Source: Android Questions

LEAVE A COMMENT