Firebase Firestore Using View Models and LiveData (Kotlin, Android)

Here we will see how to use the MVVM architecture to use Firebase Firestore as backend. We will try to operate our Database requests using View Model and a Repository.

Step 1

Add Dependencies.

In your project level gradle file, under buildscript -> dependencies, add Google Services

In your app level gradle file, under dependencies, add Firebase dependencies

Step 2

Now we will create a Model. We will try to add different addresses to Firestore. A sample Address Model is given below.

Step 3

Now create the Firebase repository to manage the database.

Now we have created access to saving , getting and deleting addresses in the Firestore database.

Step 4

Create FirestoreViewModel that extends ViewModel. This will store all the data related to Activities and Fragments.

Now we have created the ViewModel for Firestore. We can now call the needed functions from our Activity or Fragment.

Step 5

Call the needed functions from FirestoreViewModel in the following way:

Get FirestoreViewModel in this way:

Get all the addresses:

Add a new Address to Firestore

Delete an existing address from Firestore

So, this was a quick way to use ViewModels for Firestore Database operation.