Skip to content

Instantly share code, notes, and snippets.

@kibotu
Created June 25, 2024 06:48
Show Gist options
  • Save kibotu/bd4eb5d37410a18311d200103a827df8 to your computer and use it in GitHub Desktop.
Save kibotu/bd4eb5d37410a18311d200103a827df8 to your computer and use it in GitHub Desktop.
WaitForLifecycleEvent
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import de.check24.profis.partner.shared.logger.ProfiLogger
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun Lifecycle.waitForLifecycleEvent(event: Lifecycle.Event) = suspendCancellableCoroutine { continuation ->
val observer = object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
if (event != Lifecycle.Event.ON_CREATE) return
continuationResume()
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
if (event != Lifecycle.Event.ON_START) return
continuationResume()
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
if (event != Lifecycle.Event.ON_RESUME) return
continuationResume()
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
if (event != Lifecycle.Event.ON_PAUSE) return
continuationResume()
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
if (event != Lifecycle.Event.ON_STOP) return
continuationResume()
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
if (event != Lifecycle.Event.ON_DESTROY) return
continuationResume()
}
private fun continuationResume() {
continuation.resume(Unit) {
ProfiLogger.i(it.message.orEmpty())
}
removeObserver(this)
}
}
addObserver(observer)
continuation.invokeOnCancellation {
removeObserver(observer)
}
}
suspend fun Lifecycle.waitForOnResume() = waitForLifecycleEvent(Lifecycle.Event.ON_RESUME)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment