Skip to content

Instantly share code, notes, and snippets.

@saket
Last active November 19, 2024 15:11
Show Gist options
  • 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.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
}
}
}
}
@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