State Management in Jetpack Compose

Jul 12, 2024

State Management in Jetpack Compose

Overview

  • Presenters: Alejandra Stamato and Manuel Vivo
  • Purpose: Workshop to understand state management in Jetpack Compose through a Codelab.
  • App in focus: A wellness app with a water counter and a list of wellness tasks.

Key Concepts

State Definition

  • State: Any value that changes over time, such as values from a Room database or variables in a class.
  • State in Wellness App: Number of glasses of water drunk, list of tasks, task completion status.

State in Compose

  • Function: Composable functions transform state data into a UI.
  • UI Update Loop: State is displayed -> Event happens -> Event handler changes state -> UI updates with new state.
  • State Tracking: Compose recomposes affected composable functions to update the UI.

MutableState

  • Using MutableState: mutableStateOf wraps a state value to be observed and tracked by Compose.
  • Remember API: remember retains state across recompositions, while rememberSaveable retains state across configuration changes.
  • Delegated Properties: Use by keyword for simpler state management syntax.

Practical Implementation

Wellness App Sections

  1. Water Counter
    • Initial setup with a hardcoded count (static state).
    • Adding events to update count (dynamic state).
    • Using remember and mutableStateOf to track count state.
    • Handling configuration changes with rememberSaveable.
  2. List of Wellness Tasks
    • Implementing task items with check and delete buttons.
    • Stateless vs. stateful composables: State hoisted to the list level.
    • Using LazyColumn for an infinite list of tasks.
    • Preserving task state with rememberSaveable.

State-Driven UI

  • Declarative UI: UI described by current state conditions, recomposed as state changes.
  • Managing State in Lists: Using toMutableStateList() for making lists observable.

ViewModels

  • Introduction: Handles UI state and business logic, lives beyond composable lifecycle.
  • Integration & Benefits: ViewModels in Compose ensure state persistence across configuration changes.
  • Refactor Example: Migrating list state and behaviors to ViewModel.

Best Practices

  • State Hoisting: Moving state to composable’s caller to decouple state management.
  • Single Source of Truth: Avoid passing MutableState around directly to ensure a single source of truth.
  • ViewModel Usage: Recommended only at screen-level composables, avoid passing ViewModel down the composable tree.
  • Declarative UI Principles: Describe UI conditions reactively instead of imperatively.

Additional Resources

  • Jetnews Sample App: For best practices in a Compose app.
  • Compose Documentation: More on state management, architecture, and ViewModel integration.

Congratulations on completing the workshop! 🎉