Skip to content

Instantly share code, notes, and snippets.

@zarini
Last active September 4, 2021 06:54
Show Gist options
  • Save zarini/4ba6e032464e673a64958660e3307b6c to your computer and use it in GitHub Desktop.
Save zarini/4ba6e032464e673a64958660e3307b6c to your computer and use it in GitHub Desktop.
Compose back button handler
@Composable
fun BackButtonAction(onBackPressed: () -> Unit) {
CompositionLocalProvider(
localBackPressedDispatcher provides (
LocalLifecycleOwner.current as ComponentActivity
).onBackPressedDispatcher
) {
BackButtonHandler {
onBackPressed.invoke()
}
}
}
@Composable
private fun BackButtonHandler(
enabled: Boolean = true,
onBackPressed: () -> Unit
) {
val dispatcher = localBackPressedDispatcher.current ?: return
val backCallback = remember {
object : OnBackPressedCallback(enabled) {
override fun handleOnBackPressed() {
onBackPressed.invoke()
}
}
}
DisposableEffect(dispatcher) {
dispatcher.addCallback(backCallback)
onDispose {
backCallback.remove()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment