Currently, in my Android project, I am reading and writing data into Firebase Realtime Database in many fragments and activities. I was wondering if is there a way to condense all my reading and writing to one class or ViewModel. However, some of my fragments already have view models and I read that having 2 view models isn’t good practice. I am also wondering, is having many valueEventListeners bad?
So my questions are:
- How can I condense where I read and write data into Firebase?
- Is it better (as in cost-effective) to have fewer valueEventListeners?
- How does MVVM architecture solve this problem? (If it does)
2
Answers
If you are using MVVM architecture then you should perform all
READ/WRITE operations in the Repository class and you can call the
the method from ViewModel, Also you can use the same Repository with
multiple ViewModel If Required.
for Better understanding check –
https://medium.com/firebase-developers/android-mvvm-firestore-37c3a8d65404
Yes, you can create a single shared ViewModel object and use an instance of it for all your activities or fragments.
Since everything in Firestore it’s about the number of reads you perform, yes, if you attach fewer listeners, as also @FrankvanPuffelen mentioned in his comment, it means that you’ll end up reading less data, which in terms implies reduced costs.
It doesn’t. MVVM it’s just an architecture pattern that can help you organize the code, it doesn’t reduce Firebase costs.