I'm reading the docs about `Channel`s and I was a ...
# coroutines
a
I'm reading the docs about `Channel`s and I was a bit puzzled. In the Fan-out examples it uses extension functions on
CoroutineScope
, but in the Fan-in examples it uses suspending functions. Is there a practical difference between these two approaches? ---->
Copy code
@JvmStatic
    fun main(args: Array<String>) = runBlocking {

        val channel = Channel<String>()
        launch { sendString(channel, "foo", 200L) }
        launch { sendString(channel, "BAR!", 500L) }
        repeat(6) {
            // receive first six
            println(channel.receive())
        }
        coroutineContext.cancelChildren() // cancel all children to let main finish

    }

    suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) {
        while (true) {
            delay(time)
            channel.send(s)
        }
    }
versus
Copy code
@JvmStatic
    fun main(args: Array<String>) = runBlocking {

        val channel = Channel<String>()
        sendString(channel, "foo", 200L)
        sendString(channel, "BAR!", 500L)
        repeat(6) {
            // receive first six
            println(channel.receive())
        }
        coroutineContext.cancelChildren() // cancel all children to let main finish

    }

    fun CoroutineScope.sendString(channel: SendChannel<String>, s: String, time: Long) = launch {
        while (true) {
            delay(time)
            channel.send(s)
        }
    }
Both are doing the same if I understand the concepts correctly and also produce the same output. When should I use which?
m
Use an extension on
CoroutineScope
if the function needs to start new coroutines. Otherwise, use a suspend function if it only needs to suspend. That will let the caller decide how to run it (like with
async
,
launch
or whatever other coroutine builder you need).
­čĹŹ 1
A suspend function is also expected to perform all work before it returns, while an extension on
CoroutineScope
could fire off some work and return a
Job
for example.
a
i see, thanks for the clarification!
so i use
suspend
for simple tasks as part of impertative code
like
Copy code
val x = doThis()
val y = doThat(x)
and I use
CoroutineScope
for more involved work, which is potentially long running?