Bridge channel to a sequence

Viewed 554

This code is based on Coroutines guide example: Fan-out

val inputProducer = produce<String>(CommonPool) {
    (0..inputArray.size).forEach {
        send(inputArray[it])
    }
}

val resultChannel = Channel<Result>(10)

repeat(threadCount) {
    launch(CommonPool) {
        inputProducer.consumeEach {
            resultChannel.send(getResultFromData(it))
        }
    }
}

What is the right way to create a Sequence<Result> that will provide results?

2 Answers

I had the same problem, and in the end I came up with this rather unusual/convoluted solution:

fun Channel<T>.asSequence() : Sequence<T> {
    val itr = this.iterator()
    return sequence<Int> {
      while ( runBlocking {itr.hasNext()} ) yield( runBlocking<T> { itr.next() } )
    }
}

I do not think it is particular efficient (go with the one provided by @hotkey), but it has a certain appeal to me at least.

Related