Created
November 6, 2020 08:43
-
-
Save jcayzac/f7cf32bae5ce4cd4f4d28237c694d4d5 to your computer and use it in GitHub Desktop.
A `launch` for IDEA scratches
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
import kotlin.coroutines.* | |
/** | |
* Minimal, probably-borked implementation of `launch()`, just good enough | |
* for running in a IDEA scratch. | |
* | |
* ### Usage | |
* | |
* ```kt | |
* suspend fun main() { | |
* ...crazy coroutine stuff | |
* } | |
* | |
* launch { | |
* main() | |
* } | |
* ``` | |
*/ | |
fun launch(block: suspend () -> Unit) = | |
Launch().run { | |
block.startCoroutine(this) | |
await() | |
} | |
private class Launch : Continuation<Unit> { | |
var done = false | |
var failure: Throwable? = null | |
override val context: CoroutineContext get() = EmptyCoroutineContext | |
override fun resumeWith(result: Result<Unit>) = synchronized(this) { | |
done = true | |
try { | |
result.getOrThrow() | |
} catch (failure: Throwable) { | |
this.failure = failure | |
} | |
(this as Object).notifyAll() | |
} | |
fun await() = synchronized(this) { | |
while (true) { | |
when (val done = this.done) { | |
false -> { | |
(this as Object).wait() | |
} | |
else -> { | |
failure?.let { | |
throw it | |
} | |
return | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment