This composable (i thought) was supposed to run a ...
# compose-android
c
This composable (i thought) was supposed to run a block of code onResume of the containing activity. It seems to do that + it will run if I switch tabs, and then back to this one. Am I misunderstanding something (note: I know that new convenience methods for things like this now exist, but im debugging some older code)
Copy code
@Composable
fun StartOnResume(block: () -> Unit) {
  val lifecycle = LocalLifecycleOwner.current.lifecycle
  DisposableEffect(lifecycle) {
    val observer = LifecycleEventObserver { _, event ->
      if (event == Lifecycle.Event.ON_RESUME) {
        block()
      }
    }
    lifecycle.addObserver(observer)
    onDispose { lifecycle.removeObserver(observer) }
  }
}
s
If “Switch tabs” you mean navigating from a destination to another one, then that makes total sense yes. Navigation (at least androidx.navigation) as soon as you start any navigation even turns the local lifecycle of the screen from Resumed to created while the animation is playing, and when it settles the new one that has come on the screen will be turned back into Resumed again.
c
Interesting. I thought the lifecycle owner here was the activity and so it would only call onresume when the activitiy resumed
s
Depends where you are. LocalLifecycleOwner if you are inside a androidx.navigation composable is in fact the lifecycle of that destination’s NavBackStackEntry. See here https://x.com/ianhlake/status/1760066373571797239
c
interesting....
TIL
so the "screen" composable pretty much gets its own lifecycle
i wonder if thats sorta new, or always worked that way. will investigate
s
Always has been 🧑‍🚀 🔫 🧑‍🚀
😂 3
c
So... I was just thinking about this again. this is kinda like composeable destination are kinda like "fragments" in that they get their own lifecycle. Does that seem right to you?
s
Yeah that sounds like a reasonable parallel to draw I think. Look at this test https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:navigati[…]9?q=NavHostTest&ss=androidx%2Fplatform%2Fframeworks%2Fsupport to see how the
backStackEntry?.lifecycle?.currentState
is changing as things happen 😄
Basically as a navigation event starts, immediately no screens are in the Resumed state. The one leaving is going to Created status, the one coming in goes to Started status. When the animation is over, the new becomes Resumed. The old one then: • If it is in the backstack stays as Created • If it’s a pop, then it just gets Destroyed completely