https://kotlinlang.org logo
#compose-android
Title
# compose-android
c

Colton Idle

03/11/2024, 7:11 AM
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

Stylianos Gakis

03/11/2024, 8:36 AM
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

Colton Idle

03/11/2024, 9:14 AM
Interesting. I thought the lifecycle owner here was the activity and so it would only call onresume when the activitiy resumed
s

Stylianos Gakis

03/11/2024, 9:42 AM
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

Colton Idle

03/11/2024, 11:35 AM
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

Stylianos Gakis

03/11/2024, 11:47 AM
Always has been 🧑‍🚀 🔫 🧑‍🚀
😂 3
c

Colton Idle

03/13/2024, 11:07 PM
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

Stylianos Gakis

03/13/2024, 11:29 PM
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
2 Views