Derek Berner
07/09/2019, 1:40 PMinterface TriplexChannel<I, out O> : SendChannel<I>, ReceiveChannel<O> {
data class Error<I>(val input: I, val error: Throwable)
val errors: ReceiveChannel<Error<I>>
}
@UseExperimental(ExperimentalTypeInference::class)
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
fun <I, O> CoroutineScope.triplex(
context: CoroutineContext = EmptyCoroutineContext,
capacity: Int = Channel.RENDEZVOUS,
capacityOut: Int = capacity,
capacityErrors: Int = capacity,
@BuilderInference block: suspend SendChannel<O>.(I) -> Unit
): TriplexChannel<I, O> {
val channelIn = Channel<I>(capacity)
val channelOut = Channel<O>(capacityOut)
val channelErrors = Channel<TriplexChannel.Error<I>>(capacityErrors)
GlobalScope.launch(context) {
withContext(newCoroutineContext(context)) {
for(value in channelIn) {
launch {
try {
channelOut.block(value)
} catch(e: Throwable) {
channelErrors.send(TriplexChannel.Error(value, e))
}
}
}
}
}
return object : TriplexChannel<I, O>,
SendChannel<I> by channelIn,
ReceiveChannel<O> by channelOut
{
override val errors = channelErrors
override fun close(cause: Throwable?): Boolean {
// Don't short circuit - close them both.
return channelIn.close(cause) and channelErrors.close(cause)
}
}
}