Skip to content

Instantly share code, notes, and snippets.

@saket
Created December 27, 2023 21:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saket/31d456c225b8459ba1643739cae6fd1f to your computer and use it in GitHub Desktop.
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
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
}
}
}
@saket
Copy link
Author

saket commented Dec 27, 2023

Usage:

val pagerState = rememberPagerState(...)

HorizontalPager(pagerState) { pageNum ->
  val pageLifecycleOwner = mirroringLifecycleOwner(
    mirrorMode = when (pagerState.settledPage) {
      pageNum -> LifecycleMirrorMode.MirrorParent
      else -> LifecycleMirrorMode.Override(Lifecycle.State.CREATED)
    }
  )
  CompositionLocalProvider(LocalLifecycleOwner provides pageLifecycleOwner) {
    // Your pages here.
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment