Skip to content

Instantly share code, notes, and snippets.

@jcayzac
Created November 6, 2020 08:43
Show Gist options
  • Save jcayzac/f7cf32bae5ce4cd4f4d28237c694d4d5 to your computer and use it in GitHub Desktop.
Save jcayzac/f7cf32bae5ce4cd4f4d28237c694d4d5 to your computer and use it in GitHub Desktop.
A `launch` for IDEA scratches
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