Last active
November 19, 2024 15:11
-
-
Save saket/31d456c225b8459ba1643739cae6fd1f to your computer and use it in GitHub Desktop.
A `LifecycleOwner` that can switch between mirroring of its parent's state and an overridden state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.compose.runtime.Composable | |
import androidx.compose.runtime.DisposableEffect | |
import androidx.compose.runtime.Immutable | |
import androidx.compose.runtime.remember | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleEventObserver | |
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.LifecycleRegistry | |
import androidx.lifecycle.compose.LocalLifecycleOwner | |
@Composable | |
fun mirroringLifecycleOwner(mode: LifecycleMirrorMode): LifecycleOwner { | |
val hostLifecycle = LocalLifecycleOwner.current.lifecycle | |
val mirroringOwner = remember(hostLifecycle) { | |
object : LifecycleOwner { | |
val lifecycleRegistry = LifecycleRegistry(provider = this) | |
override val lifecycle: Lifecycle get() = lifecycleRegistry | |
} | |
} | |
DisposableEffect(mode, hostLifecycle) { | |
val observer = LifecycleEventObserver { _, event -> | |
val nextState = mode.choose(hostState = event.targetState) | |
mirroringOwner.lifecycleRegistry.currentState = nextState | |
} | |
hostLifecycle.addObserver(observer) | |
onDispose { hostLifecycle.removeObserver(observer) } | |
} | |
return mirroringOwner | |
} | |
@Immutable | |
sealed interface LifecycleMirrorMode { | |
data object MirrorParent : LifecycleMirrorMode | |
data class Override(val withState: Lifecycle.State) : LifecycleMirrorMode | |
fun choose(hostState: Lifecycle.State): Lifecycle.State { | |
return if (hostState == Lifecycle.State.DESTROYED) { | |
hostState | |
} else { | |
when (this) { | |
is MirrorHost -> hostState | |
is Override -> if (hostState.isAtLeast(withAtMost)) withAtMost else hostState | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: