onLifecycleCreated
Called when this navigatable is added to the backstack.
When This Is Called
This method is invoked exactly once per lifecycle:
When navigating to this screen and it's added to the backstack
After
Store.reset()for entries that remain in the backstack (new lifecycle instance)
What You Can Do Here
Dispatch initial actions (e.g., load data)
Launch coroutines (automatically cancelled when entry is removed)
Register cleanup handlers via BackstackLifecycle.invokeOnRemoval
Observe state changes using BackstackLifecycle.selectState
Check/observe visibility via BackstackLifecycle.visibility
Cleanup Options
Recommended: Use BackstackLifecycle.invokeOnRemoval for cleanup logic
Alternative: Use try/finally in launched coroutines (runs when scope is cancelled)
Example
object ProfileScreen : Screen {
override suspend fun onLifecycleCreated(lifecycle: BackstackLifecycle) {
// Dispatch initial action if visible
if (lifecycle.visibility.value) {
lifecycle.dispatch(ProfileAction.LoadProfile)
}
// Launch coroutine (auto-cancelled on removal)
lifecycle.launch {
lifecycle.selectState<UserState>().collect { state ->
if (!lifecycle.visibility.value) return@collect
lifecycle.dispatch(ProfileAction.Update(state))
}
}
// Register cleanup handler
lifecycle.invokeOnRemoval {
launch {
val logic = selectLogic<ProfileLogic>()
logic.cleanup()
}
}
}
}Parameters
Provides entry info, visibility, dispatch, selectState, and coroutine scope