Member-only story
The Right Way to Listen Jetpack Compose State Changes
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 any changes in any component.
Here is an additional sample for the ScrollState
;
val scrollState = rememberScrollState()
LaunchedEffect(scrollState) {
snapshotFlow { scrollState.maxValue }
.collect { scrollState.animateScrollTo(it) }
}

Special thanks to CuriousCursor, and Necati Sozer.