Created
December 9, 2020 11:42
-
-
Save manuelvicnt/236e04856fbfaa3e015655dad7e9025e to your computer and use it in GitHub Desktop.
awaitClose
This file contains hidden or 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
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