'Golang pipeline pattern in Kotlin

I wanted to learn more about Kotlin coroutines and was wondering if mimicking the Go merge function example can be done in a more idiomatic way in Kotlin?

As a newbie I can just translate the merge function directly into Kotlin as follows:

fun <T> CoroutineScope.merge(vararg channels: ReceiveChannel<T>) : Channel<T> {
    val outgoing = Channel<T>()

    val jobs = channels.map { channel ->
        launch {
            for ( message in channel) {
                outgoing.send(message)
            }
        }
    }

    launch {
        jobs.joinAll()
        println("done merging")
        outgoing.close()
    }

    return outgoing
}

This does however feel like I'm writing Go in Kotlin which is probably wrong.

I'd prefer no experimental API's and functions if possible, only code you can show your boss ;-)

Here's an example of it working https://pl.kotl.in/6ErnutS2X



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source