forked from Kotlin/coroutines-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildSequence.kt
32 lines (25 loc) · 1021 Bytes
/
buildSequence.kt
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
package sequence
import kotlin.coroutines.experimental.*
@RestrictsSuspension
interface SequenceBuilder<in T> {
suspend fun yield(value: T)
}
fun <T> buildSequence(block: suspend SequenceBuilder<T>.() -> Unit): Sequence<T> = Sequence {
SequenceCoroutine<T>().apply {
nextStep = block.createCoroutine(receiver = this, completion = this)
}
}
private class SequenceCoroutine<T>: AbstractIterator<T>(), SequenceBuilder<T>, Continuation<Unit> {
lateinit var nextStep: Continuation<Unit>
// AbstractIterator implementation
override fun computeNext() { nextStep.resume(Unit) }
// Completion continuation implementation
override val context: CoroutineContext get() = EmptyCoroutineContext
override fun resume(value: Unit) { done() }
override fun resumeWithException(exception: Throwable) { throw exception }
// Generator implementation
override suspend fun yield(value: T) {
setNext(value)
return suspendCoroutine { cont -> nextStep = cont }
}
}