Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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() {
val backDispatcher = LocalBackPressedDispatcher.current
// Whenever there's a new dispatcher set up the callback
DisposableEffect(backDispatcher) {
// When the effect leaves the Composition, or there's a new dispatcher, remove the callback
onDispose {
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