Home > front end >  Where to read and write data for Firebase
Where to read and write data for Firebase

Time:08-24

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:

  1. How can I condense where I read and write data into Firebase?
  2. Is it better (as in cost-effective) to have fewer valueEventListeners?
  3. How does MVVM architecture solve this problem? (If it does)

CodePudding user response:

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

CodePudding user response:

I was wondering if is there a way to condense all my reading and writing to one class or ViewModel?

Yes, you can create a single shared ViewModel object and use an instance of it for all your activities or fragments.

Is it better (as in cost-effective) to have fewer valueEventListeners?

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.

How does MVVM architecture solve this problem?

It doesn't. MVVM it's just an architecture pattern that can help you organize the code, it doesn't reduce Firebase costs.

  • Related