Member-only story
The All-New State in Jetpack Compose
Learn how to use LiveData, observeAsState, and MutableState in Compose
In this article, we’re going to learn what state is and how it works in Jetpack Compose. While doing so, we’re going to learn some fancy things like remember
, LiveData
with observeAsState
, and Compose-specific MutableState
concepts.
Note: Jetpack Compose recently moved to Beta. This means there will no longer be any drastic changes in the API structure. So it would be a great time to learn how to work with the next-generation UI kit for Android development. Widgets in Jetpack Compose are reactive to states, so enjoy the article.
You need to install Android Studio Canary, Arctic Fox (2020.3.1) to use the Jetpack Compose Beta.
Prerequisites
Before going any further, you must have basic knowledge of how to work with Jetpack Compose. If you’re new to Compose, I highly recommend going through the following articles:
- “Jetpack Compose Components (Part 1)”
- “Build Android Layouts in JetPack Compose”
- “Theming in Jetpack Compose for Android”
- “Navigation With Jetpack Compose in Android”
Introduction
In the traditional approach to Android development, we usually write the code to find the views in the view hierarchy and update them using appropriate functions such as setText
, setImageResource
, View.GONE
, and more.
In this approach, we need to manually update the widgets of the UI based on several things like user interactions, events happening in the ViewModel
, or system-related events. This kind of manual handling will increase the chances of errors.
In Jetpack Compose, we build the UI using a set of composable functions in a declarative way. If you’re new to Jetpack Compose, read the following article before going any further (and make sure to use updated versions of Jetpack Compose libraries):