DEV Community

David
David

Posted on

LiveData Examples

So in Google Codelabs tutorial, Live observers are mentioned for passing data from the database to your activity. You are shown how to do 1 version of LiveData, which is to wrap a list in a LiveData<>, but what are some other methods and options out there? Well here I list a few examples, I have found through out the web.

First example

Is a simple Livedata that wraps around a list or item, it only changes when the database is changed in a separate manner.

alt text

Gets passed through the repository if you have it and then on to the view model:

alt text

then the viewmodel gets initialized in your activity class so you can create the observer and pass its data to your data holder.

alt text

Second Example

Passing in parameters to the LiveData

modify the dao

alt text

and at the ViewModel you need to use a second LiveData known as MutableLiveData.
This MutableLiveData will be used for passing in a query term to the original LiveData from the activity.

alt text

The only change this causes in the activity code is an extra call to set the search_term

alt text

Third Example

Passing in LiveData to a PagedList. Uses android architecture Room to create a Datasource.factory method from sql.
This method is a great way to populate PagedLists, I only learned a bit about it because I mistook it for a pageAdapter when I was first learning Android.

First modify your DAO to use a datasource.

alt text

In the Viewmodel class you set up your paged list to interact with the LiveData.

alt text

Finally you set an observer and pass in your factory data to an adapter from the pagedList, this is basically the same as example 1s.

alt text

While example 1 and 2 will generally work as is, example 3 tends to be harder to implement depending on your data , but for now this is the simplest example I could write up. without any extras that are usually associated with the PagedList.

Top comments (0)