BackstackLifecycle

class BackstackLifecycle(val entry: NavigationEntry, navigationStateFlow: StateFlow<NavigationState>, storeAccessor: StoreAccessor, lifecycleScope: CoroutineScope) : CoroutineScope(source)

Lifecycle manager for a screen in the backstack.

Provides access to visibility status, state selection, action dispatching, and a coroutine scope tied to the entry's lifecycle. Coroutines launched via this scope are automatically cancelled when the entry is removed from the backstack.

Lifecycle Flow

Normal Navigation:

  1. Screen added to backstack → Navigatable.onLifecycleCreated called once

  2. Screen remains in backstack → No lifecycle events (observe visibility for changes)

  3. Screen removed from backstack → invokeOnRemoval handlers called once, then scope cancelled

With Store.reset():

  1. Store.reset() called → invokeOnRemoval handlers for all existing entries

  2. Observation restarts → Navigatable.onLifecycleCreated called once for each backstack entry

  3. Fresh lifecycle instances created with clean state

Each reset is idempotent - multiple resets follow the same pattern.

Example Usage

override suspend fun onLifecycleCreated(lifecycle: BackstackLifecycle) {
// Check current visibility
if (lifecycle.visibility.value) {
lifecycle.dispatch(MyAction.LoadData)
}

// Observe visibility changes - auto-cancelled when entry is removed
lifecycle.launch {
lifecycle.visibility.collect { isVisible ->
println("Visibility changed: $isVisible")
}
}

// Register cleanup when removed from backstack
lifecycle.invokeOnRemoval {
// `this` is StoreAccessor — non-suspend context
// Must use launch for suspend work (fire-and-forget)
launch {
val logic = selectLogic<SomeLogic>()
logic.cleanup()
dispatch(SomeAction.Removed)
}
}
}

Constructors

Link copied to clipboard
constructor(entry: NavigationEntry, navigationStateFlow: StateFlow<NavigationState>, storeAccessor: StoreAccessor, lifecycleScope: CoroutineScope)

Properties

Link copied to clipboard
Link copied to clipboard

The navigation entry for this navigatable

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
val visibility: StateFlow<Boolean>

StateFlow indicating whether this entry is currently visible. Use .value for current state or collect for changes.

Functions

Link copied to clipboard
fun dispatch(action: ModuleAction)
Link copied to clipboard

Register a callback to be invoked when this entry is removed from the backstack.

Link copied to clipboard
inline suspend fun <L : ModuleLogic> selectLogic(): L
Link copied to clipboard
inline suspend fun <S : ModuleState> selectState(): StateFlow<S>