Created
October 7, 2021 09:33
-
-
Save kibotu/71595eb11911b2c95888b0b86e76077b to your computer and use it in GitHub Desktop.
waitForLifecycleEvent
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
@OptIn(ExperimentalCoroutinesApi::class) | |
suspend fun Lifecycle.waitForLifecycleEvent(event: Lifecycle.Event) = suspendCancellableCoroutine<Unit> { 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment