What is LiveData?

LiveData is an observable data holder class. It is also lifecycle-aware, which means that it respects the lifecycle of the other app components, such as activities, fragments and services. It notifies only active observers, represented by the Observer class. Using LiveData has a lot of benefits, some of which are:
  • Ensures the UI matches the data state
  • One of the greatest things about using the reactive approach is that you don’t need to update the UI every time the data changes. Instead, the active observers are notified for data changes and they update the UI. This saves a lot of manual updates and time developing an application.
  • Up to date data
  • If an activity goes in the background and then comes back to the screen, its observers are notified if there are changes in the data. This way the observers update the UI of the activity with the newest data available.
  • No memory leaks
  • Observers are bound to specific lifecycle objects and clean up themselves after the lifecycle is destroyed.
  • No crashes due to stopped activities
  • If an activity is inactive, then the observers in the activity don’t receive LiveData events because LiveData respects the lifecycle of the app components.

LiveData works great in combination with the other Architecture Components. In the next chapters we will see examples of writing SQL queries which return LiveData objects and examples of using LiveData in ViewModel and Repository.

Share :
Share :

Weitere Beiträge

Repository in Android’s MVVM architecture

Repository is a class which purpose is to provide a clean API for accessing data. What that means is that the Repository can gather data from different data sources(different REST APIs, cache, local database storage) and it provides this data to the rest of the app.

Weiterlesen »
Room. Reactive queries

Room has great integration with LiveData. Results from SQL queries can be easily wrapped in LiveData container. This way LiveData can be observed in the UI. When the data is changed in the database, all active observers get notified and update the corresponding views.

Weiterlesen »
Using Room in CryptoOracle

In the Android application CryptoOracle the data is persisted in SQLite database. The reasons are two:
The application can still work and show persisted data when there is no internet connection.

Weiterlesen »