simple-stack
simple-stack copied to clipboard
TargetSdkVersion 34 replaces onBackPressed() with OnBackInvokedCallback
With the "advent" of OnBackPressedDispatcher
, we already had to do this:
class MainActivity : AppCompatActivity(), SimpleStateChanger.NavigationHandler {
private val backPressedCallback = object: OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (!Navigator.onBackPressed(this@MainActivity)) {
this.remove() // this is the only safe way to invoke onBackPressed while cancelling the execution of this callback
onBackPressed() // this is the only safe way to invoke onBackPressed while cancelling the execution of this callback
[email protected](this) // this is the only safe way to invoke onBackPressed while cancelling the execution of this callback
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
// ...
onBackPressedDispatcher.addCallback(backPressedCallback) // this is required for `onBackPressedDispatcher` to work correctly
// ...
}
@Suppress("RedundantModalityModifier")
override final fun onBackPressed() { // you cannot use `onBackPressed()` if you use `OnBackPressedDispatcher`
super.onBackPressed() // `OnBackPressedDispatcher` by Google effectively breaks all usages of `onBackPressed()` because they do not respect the original contract of `onBackPressed()`
}
}
However, now, onBackPressed()
is deprecated in Android Tiramisu, replaced with onBackPressedCallback
and onBackInvokedCallback
, which seem to have the same design problems as OnBackPressedDispatcher
: namely, that once you registered to receive a callback and you have received said callback, you can't cancel the request.
Clearly, the people at Google writing this code have never heard of event bubbling, which has worked in most UI frameworks in the past 15+ years.
However, this means we might need to bite the bullet and replace the current event-bubbling approach of ScopedServices.HandlesBack
with tinkering with exposing if a service on top is currently handling back or not.
This is quite a heavy change and will require Android T to come out.