mardi 23 octobre 2018

Store Firestore objects in Android ViewModel

I'm creating a new Android project, using Kotlin, ViewModels, DataBinding and Firestore. I'm a bit confused how I should go forward with this, mainly how to handle/store Firestore documents/references. As example, I will use a GroceryList app, in which you can add items to your list.

At some point, you select one of your lists, and go to some DetailFragment. I store my selected GroceryList in a selectedGroceryList object in my ViewModel. In my xml, I can use this object in ViewModel to display the name, the items in the list, etc. For instance, I can display the name in a textview with android:text="@{viewModel.selectedGroceryList.name}".

Up to this point, I'm a happy! However.. what if we want to write?

Imagine I want to add 'Apples' to my grocerylist. I can add it to the groceryList in the ViewModel, but that doesn't add it to my Firestore. To do that, I would need the Firestore Documentreference. So what is the best way to save this Firestore docref? Should I save this ref to my ViewModel next to the groceryList, and always store the object itself, and the reference to it? Or should I only store the reference, and fetch the object from my Firestore db every time I need it?

Aucun commentaire:

Enregistrer un commentaire