top of page
  • Writer's pictureDon Peter

LiveData: An Observable Data Holder for Android Apps


LiveData: An Observable Data Holder for Android Apps

LiveData is an observable data holder class in Android as part of androidx package. It notifies the UI about data changes, but unlike its regular counterparts, it's lifecycle-aware. This means that it adheres to the lifecycles of activities, fragments, and other app components, ensuring that the data updates only reach the active observers, thus preventing memory leaks.


Consider a use-case where the app displays a screen with the latest blog posts. With LiveData, you,


  1. Fetch the blog posts data from database or API call and set it to a MutableLiveData instance.

  2. Create an Observer object in your activity/fragment to update the UI.

  3. Observe the LiveData object using observe().


Whenever the blog post data changes (due to network calls, etc.), only the active activity/fragment receives the update. If it's in the background, it'll automatically receive the latest data when it resumes. No more manual lifecycle handling or data redundancy.


Working with LiveData

Following steps will help you get started with implementing a LiveData instance in a Kotlin based android app using MVVM architecture. Here we are using LiveData to update the UI when the data changes at the source.


  1. Create a LiveData instance: In MVVM architecture, data is fetched in a ViewModel class. Create a LiveData instance in your ViewModel class.

  2. Create an Observer object: Define the observer, listen to LiveData and update the UI based on data changes.

  3. Attach the Observer: Use observe() with the relevant LifecycleOwner to connect the Observer to the LiveData object.


Defining LiveData in a ViewModel class (MVVM architecture)


class UserViewModel : ViewModel() 
	// MutableLiveData to hold post data
	private val _posts = MutableLiveData<List<Post>>()
	val posts: LiveData<List<Post>> 
		get() = _posts
	// Fetch posts from a repository (replace with your implementation)
	fun fetchPosts() {
		//This will be a function call to repository class to fetch data
        val dummyPosts = listOf(
            Post(1, "Title 1", "Content 1"),
            Post(2, "Title 2", "Content 2")
        )
        _posts.postValue(dummyPosts) // Update LiveData with fetched posts from a worker thread.

    }

}
  • We define a MutableLiveData called _posts to hold the list of Post objects.

  • We expose a public posts LiveData that other components can observe.

  • The fetchPosts() method simulates fetching posts from a repository and updates the _posts value using postValue().

Observing LiveData


class UserPostsActivity : AppCompatActivity() {
    private val model: UserViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

		// Update your UI with the list of posts
        val postObserver = Observer<List<Post>> { posts ->
            recyclerView.adapter = PostAdapter(posts) // Update your UI with the list of posts
        }
		
		// Observe the posts LiveData with UserPostActivity as the lifecycleowner.
        model.posts.observe(this, postObserver)

		//fetch the post data.
		model.fetchPosts()
    }
}

  • We get a reference to the UserViewModel.

  • We define an Observer that receives the list of Post objects when the posts LiveData changes.

  • In onCreate(), we observe the posts LiveData using observe() and the current LifecycleOwner (UserViewModel).

  • When new data arrives, the postObserver updates the UI, e.g., by setting the adapter for a RecyclerView with the list of posts.


This is a basic example that demonstrates how LiveData can simplify data management and improve responsiveness of the UI in a Kotlin based Android app. Remember to adapt it to your specific data and UI needs.


Update LiveData objects using setValue() from the main thread and postValue() from a worker thread.

Benefits of using LiveData in MVVM


  • Separation of concerns: ViewModel manages data and updates LiveData, while the activity/fragment handles UI.

  • Lifecycle awareness: Only active components receive data updates, preventing crashes and unnecessary calculations.

  • Single source of truth: posts LiveData acts as the central source for post data, ensuring consistency across the UI.

  • Simplified UI updates: Observer handles data changes and updates the UI automatically.


Using MediatorLiveData


MediatorLiveData is a special type of LiveData in Android, combining data from multiple LiveData sources and creating a single unified information. 


It's useful when you need to:

  • Merge data from multiple sources: Imagine displaying comments and reactions on a post. You'd have separate LiveData objects for both, and MediatorLiveData can combine them into a single "post details" feed.

  • Respond to complex data conditions: You can define custom logic based on values from different sources. For example, show a "New" badge on a post only if both comments and reactions have updates.

  • Simplify data access: Instead of observing multiple sources, you just observe the MediatorLiveData, making your work flow cleaner and more centralized.


Common Scenarios to use LiveData


  • Use LiveData with Room's observable queries to keep your UI in sync with the database.

  • Combine LiveData with Kotlin coroutines for asynchronous data handling especially when making API calls.

  • Leverage MediatorLiveData to merge multiple LiveData sources for unified data access.


LiveData is a powerful tool that simplifies data management, improves UI responsiveness and help avoid memory related issues like leaks.



Blog for Mobile App Developers, Testers and App Owners

 

This blog is from Finotes Team. Finotes is a lightweight mobile APM and bug detection tool for iOS and Android apps.

​

In this blog we talk about iOS and Android app development technologies, languages and frameworks like Java, Kotlin, Swift, Objective-C, Dart and Flutter that are used to build mobile apps. Read articles from Finotes team about good programming and software engineering practices, testing and QA practices, performance issues and bugs, concepts and techniques. 

bottom of page