I am developing an application that fetches some documents from the Cloud Firestore and shows the contents of the documents in a RecyclerView. I want to follow the principle of separation of concern, and therefore using the MVVM architecture to build the app. I have implemented a Data class model and the adapter for the RecyclerView using the FirestoreRecyclerAdapter.
I have already worked on a guided project which used MVVM architecture with LiveData and Room. In that project, the adapter implemented had an ArrayList which held all the data which was in turn used to populate the RecyclerView.
viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(NoteViewModel::class.java)
viewModel.allNotes.observe(this, { list->list?.let{
adapter.updateList(it)}
})
Similarly, I have worked on a project which used Firestore but did not employ the MVVM architecture. In the latter one, the RecyclerView got inflated with data without passing any data to any collection whatsoever. It did not even use LiveData but the changes in Firestore were reflected instantly (which I believe is one of many benefits of Cloud Firestore).
postDao = PostDao()
val postcollection = postDao.postCollections
val query = postcollection.orderBy("createdAt", Query.Direction.DESCENDING)
val recyclerviewOptions = FirestoreRecyclerOptions.Builder<Post>().setQuery(query, Post::class.java).build()
adapter = PostAdapter(recyclerviewOptions)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
As in the code above, simply passing the collection to the adapter inflated the RecyclerView.
But now in this project where I want to implement the architecture, I am having an issue with the ViewModel class. What should it contain? And how do I use the FirestoreRecyclerOptions with the ViewModel? Do I need a collection (like a List or an ArrayList) to wrap the data from the DAO in the LiveData? Or do I need the LiveData at all? The reference docs state that I should use MutableLiveData on some object or collection, and then I should have a method to update the list every time the data changes. There is also an observer method that is implemented. But I don't see any explanation about Firestore or how the FirestoreRecyclerAdapter is even working. What I need is what do I need to implement in the ViewModel class in respect to MutableLiveData on collections from the database and update functions in the FirestoreRecyclerAdapter in the context of Cloud Firestore.