Skip to content

Instantly share code, notes, and snippets.

@walnashgit
Created May 6, 2021 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walnashgit/8004c9fbf437a1f9f8b87c4d797443fc to your computer and use it in GitHub Desktop.
Save walnashgit/8004c9fbf437a1f9f8b87c4d797443fc to your computer and use it in GitHub Desktop.
@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