addamsson
04/25/2019, 12:51 PMCoroutineScope
, but in the Fan-in examples it uses suspending functions. Is there a practical difference between these two approaches? ---->
@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
@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?marstran
04/25/2019, 1:03 PMCoroutineScope
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).CoroutineScope
could fire off some work and return a Job
for example.addamsson
04/25/2019, 6:19 PMsuspend
for simple tasks as part of impertative codeval x = doThis()
val y = doThat(x)
CoroutineScope
for more involved work, which is potentially long running?