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

Deepak Prasad
Feb 24, 2019 · 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 ''

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

// Firebase Core
implementation ''
implementation ''

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 all the addresses:

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


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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store