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

Deepak Prasad
Feb 24 · 1 min read

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

classpath 'com.google.gms:google-services:4.2.0'

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

// Firebase Core
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.firebase:firebase-firestore:18.0.1'

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:

val firestoreViewModel = ViewModelProviders.of(appContext)
      .get(FirestoreViewModel::class.java)

Get all the addresses:

firestoreViewModel.getSavedAddresses().observe(this, Observer { it->
    savedAddresses = it
    
})

Add a new Address to Firestore

firestoreViewModel.saveAddressToFirebase(addressItem)

Delete an existing address from Firestore

firestoreViewModel.deleteAddress(addressItem)

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