https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

ghedeon

01/21/2019, 12:47 PM
Trying to understand why it's never completed:
Copy code
fun main(){
    runBlocking{
    	foo().consumeEach{ println(it) }
    }
}

suspend fun foo(): ReceiveChannel<Int> = coroutineScope {
    produce<Int>{
		channel.send(42)
               channel.close()
    }
}
m

marstran

01/21/2019, 12:53 PM
You are creating a new coroutine scope inside
foo
which will wait until all child coroutines are completed. However, the
produce
-coroutine will never complete because it suspends when you send 42 (because it's default capacity is 0).
👍 1
It will work if you change your
foo
function to this:
Copy code
fun CoroutineScope.foo(): ReceiveChannel<Int> = produce<Int>{
    channel.send(42)
    channel.close()
}
That will make you reuse the scope created by
runBlocking
.
g

ghedeon

01/21/2019, 1:06 PM
yeah, that's how I'm doing it now. I just somehow assumed that if
runBlocking{ produce{} }
works, then
runBlocking{ coroutineScope{ produce{} } }
will work as well, because
coroutineScope
inherits the parent's scope...
g

gildor

01/21/2019, 1:22 PM
Empty will also work, but if you add send it will suspend forever (something like deadlock)
g

ghedeon

01/21/2019, 1:32 PM
got it.
coroutineScope
is suspended and
send
as well, so they block each other.
g

gildor

01/21/2019, 2:28 PM
Yes, coroutineScope waits all child coroutines
3 Views