Jetpack Libraries – LiveData, ViewModel, and Navigation Component - Textnotes

Jetpack Libraries – LiveData, ViewModel, and Navigation Component


Learn about Jetpack Libraries, including LiveData, ViewModel, and Navigation Component, which make Android development more efficient and easier. Understand how each component simplifies app development and enhances UI management.

Jetpack Libraries is a collection of software libraries, tools, and architectural components provided by Google to make Android development faster and easier. These libraries help developers handle common app development tasks, such as managing UI data, navigation, lifecycle awareness, and more, in a way that leads to better architecture and maintainability.

In this tutorial, we’ll dive into three core Jetpack components:

  1. LiveData
  2. ViewModel
  3. Navigation Component

i) LiveData – Observable Data Holder Class

LiveData is an observable data holder class that is lifecycle-aware. This means that LiveData only updates active UI components, preventing memory leaks and unnecessary updates when components (such as activities and fragments) are not in an active state.

How to Use LiveData

  1. Add Dependencies:

Ensure you add the necessary dependencies in your build.gradle file:


implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
  1. Creating LiveData:

You can create a LiveData object that holds the data you want to observe. For example, you might want to display a list of users in your app. You can define a LiveData object in your ViewModel:


public class UserViewModel extends ViewModel {
private MutableLiveData<List<User>> users = new MutableLiveData<>();

public LiveData<List<User>> getUsers() {
return users;
}

public void setUsers(List<User> userList) {
users.setValue(userList); // Update the LiveData
}
}
  1. Observing LiveData:

To observe changes in LiveData, you’ll use an Observer in your activity or fragment. The observer is notified whenever the data held by the LiveData object is updated.


UserViewModel userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

userViewModel.getUsers().observe(this, new Observer<List<User>>() {
@Override
public void onChanged(List<User> users) {
// Update UI here
}
});
  1. Benefits of LiveData:
  2. Automatically stops observing data when the associated lifecycle (like an activity or fragment) is stopped, thus preventing memory leaks.
  3. Easy to handle UI updates in response to data changes, without manually managing lifecycle events.

ii) ViewModel – Lifecycle-Aware Data Holder

The ViewModel class is designed to store and manage UI-related data in a lifecycle-conscious way. It helps to ensure that data is not lost during configuration changes (such as when the device is rotated).

How to Use ViewModel

  1. Creating a ViewModel:

A ViewModel is a class that holds and manages UI-related data in a lifecycle-conscious way. It survives configuration changes like screen rotations.


public class UserViewModel extends ViewModel {
private MutableLiveData<List<User>> users = new MutableLiveData<>();

public LiveData<List<User>> getUsers() {
return users;
}

public void setUsers(List<User> userList) {
users.setValue(userList);
}
}
  1. Accessing ViewModel in Activities or Fragments:

To use the ViewModel, you can get an instance of it using the ViewModelProvider:


UserViewModel userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
  1. Why Use ViewModel?
  2. ViewModel separates the UI data from the UI controller (activity or fragment), making your code easier to maintain and test.
  3. It is lifecycle-aware, meaning it preserves data even when the activity is recreated due to configuration changes (like screen rotations).
  4. ViewModel doesn’t need to be re-created when the device is rotated, preventing data loss and unnecessary network calls.

iii) Navigation Component – Simplifying Navigation Between Fragments

The Navigation Component simplifies the implementation of navigation in Android apps. It provides a consistent way to handle navigation between fragments and activities, making it easier to manage complex navigation patterns and improve app architecture.

How to Use Navigation Component

  1. Add Dependencies:

Add the Navigation Component dependencies in your build.gradle file:


implementation 'androidx.navigation:navigation-fragment-ktx:2.3.1'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.1'
  1. Define a Navigation Graph:

The Navigation Graph is an XML resource file that defines all the possible navigation paths within your app. Each fragment or activity is a destination, and the navigation actions between them are represented by actions.

Create a nav_graph.xml file under res/navigation/:


<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/nav_graph"
android:label="nav_graph"
app:startDestination="@id/homeFragment">

<fragment
android:id="@+id/homeFragment"
android:name="com.example.app.HomeFragment"
android:label="Home" >
<action
android:id="@+id/action_homeFragment_to_detailsFragment"
app:destination="@id/detailsFragment" />
</fragment>

<fragment
android:id="@+id/detailsFragment"
android:name="com.example.app.DetailsFragment"
android:label="Details" />
</navigation>
  1. Navigating Between Fragments:

To navigate between fragments, you can use the NavController class, which is linked to the NavHostFragment.


NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
navController.navigate(R.id.action_homeFragment_to_detailsFragment);
  1. Using Navigation UI:

To set up the ActionBar or Toolbar to automatically handle the Up button and other navigation actions, you can use the NavigationUI helper:


NavigationUI.setupActionBarWithNavController(this, navController);
  1. Benefits of Navigation Component:
  2. Simplifies navigation between fragments and activities with a single NavController.
  3. Handles back stack management automatically, so you don’t need to manage the back stack manually.
  4. Allows deep linking and managing navigation from multiple sources, such as notifications or web links.
  5. Reduces boilerplate code for fragment transactions.

Conclusion

In this tutorial, we have covered three essential Jetpack Libraries: LiveData, ViewModel, and the Navigation Component. These components significantly improve the development process by simplifying lifecycle management, UI data handling, and navigation:

  1. LiveData helps manage and observe data in a lifecycle-conscious way.
  2. ViewModel stores UI-related data in a way that survives configuration changes.
  3. Navigation Component provides a consistent, easy way to manage navigation between fragments and activities.

By integrating these libraries into your Android apps, you can ensure better performance, maintainability, and ease of navigation across complex app architectures.