Skip to content

Flow integration with compose

Flow Integration with Compose Deep Dive

Overview

Compose commonly consumes StateFlow and other Flows from ViewModel layers. This section focuses on lifecycle-aware collection and snapshot bridging.

Core Concepts

  • collect flow to UI state
  • lifecycle-aware collection on Android screens
  • separate state streams from one-off event streams

Runtime Internals

Flow emissions update Compose State, which invalidates dependent scopes and triggers recomposition scheduling.

Composition / Recomposition Flow

  • collector receives emission
  • state holder updates
  • dependent composables recompose
  • unchanged branches may still be skipped

State Management

Prefer immutable UiState and explicit event channels for navigation/snackbar.

Code Examples

@Composable
fun HomeRoute(viewModel: HomeViewModel) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    HomeScreen(state = state, onRetry = viewModel::retry)
}

Common Interview Questions

  • Q: collectAsState vs collectAsStateWithLifecycle? A: Start from delivery semantics: use StateFlow for durable state, SharedFlow or Channel for transient events, and lifecycle-aware collection to prevent duplicate work.
  • Q: How to model one-time events safely? A: Answer from runtime mechanics: state ownership, recomposition triggers, effect lifecycle, and frame-time impact measured with tooling.
  • Q: Why use snapshotFlow? A: Explain runtime behavior: what invalidates state, how recomposition is scoped, where side effects live, and how to verify frame stability with profiler traces.

Production Considerations

  • avoid collecting high-frequency streams without need
  • debounce/filter upstream when possible
  • verify cancellation when screen leaves foreground

Performance Insights

Excess emissions with large UI models can amplify recomposition work. Consider state granularity and emission strategy.

Senior-Level Insights

Senior candidates should explain end-to-end data flow from repository emission to recomposition behavior and lifecycle management.