The Right Way to Listen Jetpack Compose State Changes
Published in
2 min readJul 27, 2024
I’ve published a post about “How to Reliably Detect BottomSheet State Changes in Jetpack Compose” 3 days ago and thanks to the community I learned that there’s a better way to listen jetpack compose states.
I’ll use the same scenario and the same sample code to have a better comparison.
The scenario
You have a BottomSheetScaffold
in Jetpack Compose, and you need to trigger an action when the bottom sheet is hidden.
What we have
val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(
bottomSheetState = rememberStandardBottomSheetState(
initialValue = SheetValue.Expanded,
),
)
BottomSheetScaffold(
modifier = modifier,
scaffoldState = bottomSheetScaffoldState,
// ... ,
) {
// ...
}
Solution
snapshotFlow is the solution.
LaunchedEffect(bottomSheetScaffoldState.bottomSheetState) {
snapshotFlow { bottomSheetScaffoldState.bottomSheetState.currentValue }
.collect {
if (it == SheetValue.Hidden) {
isBottomSheetHidden.value = true
}
}
}
The good thing about the snapshotFlow
is it is for all of the jetpack compose states. It is the silver bullet to listen…