collectAsStateWithLifecycle vs collectLatest vs produceState
1) collectAsStateWithLifecycle
Purpose: Observe ViewModel Ul state safely Use when your ViewModel exposes StateFlow.
val uiState by
viewModel.uiState.collectAsStateWithLifecycle() What it does:
Starts collecting when screen is visible
Stops when app goes to background
Resumes automatically
• Prevents wasted work & battery drain
2) collectLatest
Purpose: Cancel outdated Ul work Use inside LaunchedEffect. LaunchedEffect(Unit) {
viewModel.searchResults.collectLatest { listState.animateScrollToltem (0)
}
If a new value arrives:
Old work is cancelled immediately.
Perfect for:
search typing
animations
scrolling
live updates
3) produceState Purpose: Convert async/callback sources →
Purpose: Convert async/callback sources →
Compose State
val location by produceState(null) { locationClient.startUpdates { value = it } awaitDispose { locationClient.stopUpdates() }
}
Best use cases:
GPS location
sensors
bluetooth
media player progress
Firebase listeners
#AndroidDev #JetpackCompose
Comments
Post a Comment