Skip to content

Instantly share code, notes, and snippets.

@IlyaGulya
Created April 2, 2024 14:55
Show Gist options
  • Save IlyaGulya/f6527f98540362cc311a3bc82dcedc14 to your computer and use it in GitHub Desktop.
Save IlyaGulya/f6527f98540362cc311a3bc82dcedc14 to your computer and use it in GitHub Desktop.
Lifecycle implementation that handles fragment hidden state changes
class HiddenAwareLifecycle(
fragment: Fragment,
) : LifecycleRegistry(fragment) {
init {
fragment.lifecycle.addObserver(
object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
currentState = State.CREATED
}
override fun onStart(owner: LifecycleOwner) {
currentState = State.STARTED
}
override fun onResume(owner: LifecycleOwner) {
currentState = State.RESUMED
}
override fun onPause(owner: LifecycleOwner) {
currentState = State.STARTED
}
override fun onStop(owner: LifecycleOwner) {
currentState = State.CREATED
}
override fun onDestroy(owner: LifecycleOwner) {
currentState = State.DESTROYED
}
},
)
}
fun onHiddenChanged(hidden: Boolean) {
currentState =
if (hidden) {
State.CREATED
} else {
State.RESUMED
}
}
}
class SomeFragment: Fragment() {
private val hiddenAwareLifecycle = HiddenAwareLifecycle(this)
override fun onHiddenChanged(hidden: Boolean) {
hiddenAwareLifecycle.onHiddenChanged(hidden)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment