DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Introduction to Android App Development With Kotlin: LiveData (Part 10)

Introduction to Android App Development With Kotlin: LiveData (Part 10)

Meet LiveData, the observable data holder class that is ''lifecycle aware.''

Łukasz Mądrzak user avatar by
Łukasz Mądrzak
CORE ·
May. 02, 19 · Tutorial
Like (2)
Save
Tweet
Share
10.92K Views

Join the DZone community and get the full member experience.

Join For Free

With the ability to retrieve data from your database, it seems appropriate that we display those records for the user to see in a fragment. At this stage, you may be wondering: how do we effectively return this list of movies from the view model to the fragment? Or maybe you are thinking: what should happen if I make a call to the database and, at the same time, the user decides to leave my app to do something else? Should we return the data nonetheless and waste resources or should we not. Luckily, there’s a Google’s Android library we can use that will handle all those awkward edge cases for us. Hello, LiveData. 

In this tutorial, we will look into LiveData, what exactly it is, and how it fits into our application.

LiveData

 LiveDatais an observable data holder class that is lifecycle aware. “This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.”

Main advantages of using LiveData:

  • Ensures your UI matches your data state
  • No memory leaks
  • No crashes due to stopped activities
  • No more manual lifecycle handling

At this stage, it’s clear that this library will make our life easier so how do we go about using it? Luckily, we don’t have to import it because it comes included as part of lifecycle-extensions, which we imported when we first started working with the view model.

Here’s the method I use for using LiveData, which makes the most sense to me. 

First, in the view model, let’s add a private instance variable of type MutableLiveData:

val allMovies = MutableLiveData<List<Movie>>()


 MutableLiveData object type is almost the same as LiveData object except it exposes two important methods, namely setValue(T) and  postValue(T), which we will use. 

Next, we will slightly upgrade the retrieveMovies() method to return a LiveData object. We will return the allMovies instance variable we created above but downcasted to LiveData since a fragment has no business updating it. 

fun retrieveMovies(): LiveData<List<Movie>> {

    GlobalScope.launch {
        val list = mDb?.movieDao()?.getAll()
        Timber.i("retrieveMovies list count ${list?.size}")
        allMovies.postValue(list)
    }

    return allMovies
}


Notice how we are also using the postValue method to notify the observers (i.e. our fragment) of the fetched data. 

Finally, it’s time to subscribe to this LiveData object in the MovieListFragment. In the line where we called the retrieveMovies() method, all we have to add is add an observer to it

mViewModel.retrieveMovies().observe(this,  Observer {

    Timber.i("received the movies ${it.size}")

})


Run the app and watch the results

Image title

We are now observing the data using LiveData! You must admit, it was quite simple yet very powerful. The fact that we don’t have to worry about activities or fragments lifecycle is a huge relief. You can now apply this pattern to all of the data calls you will ever need to make. 


Conclusion

Today, we were introduced to an awesome library called LiveData and we put it to use. With a concrete implementation, you can now easily replicate it to add any calls to the database you may need. 

With the movies list available to us within the fragment, we should now display it. The way to do it is by using a recyclerview. More about that in the next tutorial.

The complete working code can be found in this GitHub repo where each lesson is tagged appropriately.

app Android (robot) Kotlin (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Getting a Private SSL Certificate Free of Cost
  • Distributed Tracing: A Full Guide
  • 5 Steps for Getting Started in Deep Learning
  • Create a CLI Chatbot With the ChatGPT API and Node.js

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: