Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ANR when showing bottom sheets #680

Merged
merged 2 commits into from Aug 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -37,9 +37,6 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavBackStackEntry
import androidx.navigation.compose.LocalOwnersProvider
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
Expand Down Expand Up @@ -93,8 +90,19 @@ internal fun SheetContentHost(
// want to show the sheet, and hide it when this composable leaves the composition
DisposableEffect(backStackEntry) {
scope.launch {
sheetState.internalShow()
currentOnSheetShown(backStackEntry)
// Our show call can get cancelled in which case Swipeable will move to the closest
// anchor
try {
sheetState.show()
} finally {
// If the target state is a visible state, it's fairly safe to assume that
// Swipeable will end up settling in that state
if (sheetState.targetValue == ModalBottomSheetValue.Expanded ||
sheetState.targetValue == ModalBottomSheetValue.HalfExpanded
) {
currentOnSheetShown(backStackEntry)
}
}
}
onDispose {
scope.launch {
Expand Down Expand Up @@ -127,20 +135,6 @@ private fun EmptySheet() {
Box(Modifier.height(1.dp))
}

// There is a race condition in ModalBottomSheetLayout that happens when the sheet content
// changes due to the anchors being re-calculated. This causes an animation to run for a
// short time. Re-running the animation when it is cancelled works around this.
// b/181593642
@OptIn(ExperimentalMaterialApi::class)
private suspend fun ModalBottomSheetState.internalShow() {
try {
show()
} catch (animationCancelled: CancellationException) {
currentCoroutineContext().ensureActive()
internalShow()
}
}

// We have the same issue when we are hiding the sheet, but snapTo works better
@OptIn(ExperimentalMaterialApi::class)
private suspend fun ModalBottomSheetState.internalHide() {
Expand Down