How to use LiveData with Room and Kotlin

1_rDROHHQiiMS8iQUo-kVOkg.jpeg

In this article I am going to talk about how to use LiveData with Room and Kotlin. Room is a library which acts as a layer of abstraction over SQLite and assists android developers in building databases with the in built SQLite on the Android platform. LiveData is an observable data holder class which is life cycle aware. This means that the LiveData only updates its observers where there is an active life cycle.

LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED or RESUMED state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes. You can register an observer paired with an object that implements the LifecycleOwner interface. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED. This is especially useful for activities and fragments because they can safely observe LiveData objects and not worry about leaks-activities and fragments are instantly unsubscribed when their lifecycles are destroyed.

Here is a video about LiveData in the official YouTube Android Developers channel.

Why use LiveData?

  1. You prevent memory leaks in your application.
  2. You reduce the amount of code you write.
  3. Your data is always up to date.
  4. Your UI is always in sync with your current data value.
  5. No crashes due to stopped activities.

Getting started with Live Data and Room.

Step1: Add the dependencies for Room and LiveData to your app level build.gradle file.

//for livedata
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
//for room
implementation "androidx.room:room-runtime:2.2.5"
kapt "androidx.room:room-compiler:2.2.5"

Step2: Create your DAO using LiveData We use LiveData when we want to observe and output from the database. Here it is going to be a list of NoteEntity.

@Dao
interface NoteDao{
    @Insert
    fun insertNote(note: NoteEntity)
    @Query("SELECT * FROM notedatabase")
    fun getAllNotes(): LiveData<List<NoteEntity>>
}

We wrapped the return value of getAllNotes() with LiveData which means we'll observe it.

Step3: Observe the return value in your ViewModel (if you use MVVM) or Fragment/Activity

var noteSize: Int? = null
NoteDatabase.noteDao.getAllNotes.observe{lifeCycleOwner, Observer{it
        noteSize = it.size
    }
}

In the above code NoteDatabase.noteDao.getAllNotes returns the LiveData of notes. Using the .observe method makes you able to use the actual value of the returned LiveData. .observe takes 2 parameters:

  1. A lifecycle owner (activity or fragment)
  2. A lamda Observer{}

In the Observer{} you have the value of the LiveData as it (you can change it to whatever you want) with this it you can do whatever you want with the LiveData Value.

Now your UI will be updated automatically anytime a new note is inserted.

NOTE: You must observe the LiveData only on the UI thread else your app will crash.

Thank you for reading my article.

Here is my Twitter
And Instagram
And Linkedin