Skip to content

Commit

Permalink
ensure to keep a singule compose lifecycle owner and attach new paren…
Browse files Browse the repository at this point in the history
…t lifecycles if new ones are provided
  • Loading branch information
ekeitho committed Nov 20, 2024
1 parent bf97796 commit 953e2ab
Showing 1 changed file with 14 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ import androidx.lifecycle.LifecycleRegistry
@Composable internal fun rememberChildLifecycleOwner(
parentLifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle
): LifecycleOwner {
val lifecycleOwner = remember {
ComposeLifecycleOwner.installOn(parentLifecycle)
val owner = remember { ComposeLifecycleOwner.installOn(parentLifecycle) }
val lifecycleOwner = remember(parentLifecycle) {
owner.apply {
updateParentLifecycle(parentLifecycle)
}
}
return lifecycleOwner
}
Expand Down Expand Up @@ -56,9 +59,11 @@ import androidx.lifecycle.LifecycleRegistry
* @param parentLifecycle The parent [Lifecycle] with which this lifecycle owner should synchronize.
*/
private class ComposeLifecycleOwner(
private val parentLifecycle: Lifecycle
initialParentLifecycle: Lifecycle
) : LifecycleOwner, RememberObserver, LifecycleEventObserver {

private var parentLifecycle: Lifecycle = initialParentLifecycle

private val registry = LifecycleRegistry(this)
override val lifecycle: Lifecycle
get() = registry
Expand All @@ -79,6 +84,12 @@ private class ComposeLifecycleOwner(
}
}

fun updateParentLifecycle(lifecycle: Lifecycle) {
parentLifecycle.removeObserver(this)
parentLifecycle = lifecycle
parentLifecycle.addObserver(this)
}

override fun onStateChanged(
source: LifecycleOwner,
event: Event
Expand Down

0 comments on commit 953e2ab

Please sign in to comment.