Created
December 27, 2023 21:27
-
-
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 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.Immutable | |
import androidx.compose.runtime.getValue | |
import androidx.compose.runtime.remember | |
import androidx.compose.ui.platform.LocalLifecycleOwner | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.LifecycleRegistry | |
import androidx.lifecycle.compose.currentStateAsState | |
@Composable | |
fun mirroringLifecycleOwner(mirrorMode: LifecycleMirrorMode): LifecycleOwner { | |
val parentLifecycle = LocalLifecycleOwner.current.lifecycle | |
val parentLifecycleState by parentLifecycle.currentStateAsState() | |
val childLifecycleOwner = remember(parentLifecycle) { | |
object : LifecycleOwner { | |
val lifecycleRegistry = LifecycleRegistry(provider = this).apply { | |
currentState = mirrorMode.choose(parentLifecycleState) | |
} | |
override val lifecycle: Lifecycle get() = lifecycleRegistry | |
} | |
} | |
return childLifecycleOwner.apply { | |
lifecycleRegistry.currentState = mirrorMode.choose(parentLifecycleState) | |
} | |
} | |
@Immutable | |
sealed interface LifecycleMirrorMode { | |
data object MirrorParent : LifecycleMirrorMode | |
data class Override(val withState: Lifecycle.State) : LifecycleMirrorMode | |
fun choose(parentState: Lifecycle.State): Lifecycle.State { | |
return when (this) { | |
is MirrorParent -> parentState | |
is Override -> if (parentState.isAtLeast(withState)) withState else parentState | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: