Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created December 9, 2020 11:42
Show Gist options
  • Save manuelvicnt/236e04856fbfaa3e015655dad7e9025e to your computer and use it in GitHub Desktop.
Save manuelvicnt/236e04856fbfaa3e015655dad7e9025e to your computer and use it in GitHub Desktop.
awaitClose
public suspend fun ProducerScope<*>.awaitClose(block: () -> Unit = {}) {
...
try {
// Suspend the coroutine with a cancellable continuation
suspendCancellableCoroutine<Unit> { cont ->
// Suspend forever and resume the coroutine successfully only
// when the Flow/Channel is closed
invokeOnClose { cont.resume(Unit) }
}
} finally {
// Always execute caller's clean up code
block()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment