https://kotlinlang.org logo
#compose
Title
# compose
j

julian

06/10/2022, 3:07 AM
What would be the consequences of not
remember
-ing
backCallback
in the following? In other words, why
remember
backCallback
?
Copy code
@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()
    }
  }
}
i

Ian Lake

06/10/2022, 4:48 AM
FWIW, there's absolutely no reason you should ever write this code, since we've already written it for you, as explained in the docs: https://developer.android.com/jetpack/compose/libraries#handling_the_system_back_button
You'd want to make sure you're always capturing the correct
onBackPressed()
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)
The remember is necessary to allow for the
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-back
tl/dr, it took us a couple of releases to get
BackHandler
right, so just use that 🙂
👍🏻 1
👍 1
j

julian

06/10/2022, 5:08 AM
Thank you! I got the code from a sample illustrating effects - in particular
DisposableEffect
. 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.
👍 1
z

Zach Klippenstein (he/him) [MOD]

06/10/2022, 4:33 PM
In general, anything you do directly in a composable function will happen every time that function is recomposed. If you're instantiating a new object, then you'll create a new instance on every recomposition. Sometimes that's what you want, but often it's not. If you wrap the instantiation in a remember, it will be created the first time the composable appears in the composition and then cached and returned on future recompositions.
j

julian

06/10/2022, 4:52 PM
Thanks @Zach Klippenstein (he/him) [MOD]! And a composable can recompose, while some of its child composables skip recomposition, correct?
z

Zach Klippenstein (he/him) [MOD]

06/10/2022, 4:53 PM
Yes
🙏 1
2 Views