Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@Composable
fun BackPressHandler(onBackPressed: () -> Unit) {
// Safely update the current `onBack` lambda when a new one is provided
val currentOnBackPressed by rememberUpdatedState(onBackPressed)
// Remember in Composition a back callback that calls the `onBackPressed` lambda
val backCallback = remember {
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
currentOnBackPressed()
}
}
}
val backDispatcher = LocalBackPressedDispatcher.current
// Whenever there's a new dispatcher set up the callback
DisposableEffect(backDispatcher) {
backDispatcher.addCallback(backCallback)
// When the effect leaves the Composition, or there's a new dispatcher, remove the callback
onDispose {
backCallback.remove()
}
}
}
val LocalBackPressedDispatcher =
staticCompositionLocalOf<OnBackPressedDispatcher> { error("No Back Dispatcher provided") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment