blob: e14fea9ac97be7004191232f0712b3747db2b288 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import kotlin.coroutines.*
class IORunner : Continuation<Unit> {
var nextStep: Continuation<Unit>? = null
val eventQueue = ArrayDeque<String>()
fun _CALLED_BY_JS_onInput(str: String) {
eventQueue.addLast(str)
awake()
}
fun _CALLED_BY_JS_onWhatever() {
awake()
}
private fun awake() {
val step = nextStep
if (step != null) {
nextStep = null
step.resume(Unit)
}
}
suspend fun wait() {
return suspendCoroutine { c ->
console.log("SUSPENDING COROUTINE")
nextStep = c
}
}
override val context: CoroutineContext
get() = EmptyCoroutineContext
override fun resumeWith(result: Result<Unit>) {
if (result.isFailure) {
result.exceptionOrNull()?.printStackTrace()
} else {
println("IORunner exited successfully")
}
}
companion object {
fun runOnIO(block: suspend IORunner.() -> Unit): IORunner {
val r = IORunner()
block.startCoroutine(r, r)
return r
}
}
}
suspend fun IORunner.getOneKey(): String {
while (true) {
val x = eventQueue.removeFirstOrNull()
if (x == null)
wait()
else {
return x
}
}
}
|