julian
06/10/2022, 3:07 AMremember
-ing backCallback
in the following? In other words, why remember
backCallback
?
@Composable
fun BackButtonHandler(
enabled: Boolean = true,
onBackPressed: () -> Unit
) {
val dispatcher = localBackPressedDispatcher.current ?: return
val backCallback = remember { // <--- HERE
object : OnBackPressedCallback(enabled) {
override fun handleOnBackPressed() {
onBackPressed.invoke()
}
}
}
DisposableEffect(dispatcher) {
dispatcher.addCallback(backCallback)
onDispose {
backCallback.remove()
}
}
}
Ian Lake
06/10/2022, 4:48 AMonBackPressed()
lambda via rememberUpdatedState
and you'll want to make sure to set the enabled
state on every recomposition as part of a SideEffect
(rather than only using it for the initial value and then forgetting about it if it were to change after the fact)enabled
and onBackPressed
parameters to change without causing your dispatcher to be removed and then re-added (which would break the explicit ordering that the `OnBackPressedCallback`s need to maintain support for deeply nested callbacks as per the docs: https://developer.android.com/guide/navigation/navigation-custom-backBackHandler
right, so just use that 🙂julian
06/10/2022, 5:08 AMDisposableEffect
. But it's good to know there's a better way to handle back behavior.
That said, it's the interaction between use or non-use of remember
and composition/recomposition that I don't have a strong grasp of and I'm trying to understand better.Zach Klippenstein (he/him) [MOD]
06/10/2022, 4:33 PMjulian
06/10/2022, 4:52 PMZach Klippenstein (he/him) [MOD]
06/10/2022, 4:53 PM