-
-
Save walnashgit/8004c9fbf437a1f9f8b87c4d797443fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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