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

madsbf

02/03/2019, 10:10 AM
I'm running into an issue when using select, and I might just be missing something very simple. Maybe someone here can spot what I'm doing wrong? I have the following code:
Copy code
suspend fun select(contentMap: Map<Content, VideoContentItemHolder>) = coroutineScope {
    select<Content> {
        contentMap.forEach { content, itemHolder ->
            launch { itemHolder.onClick() }.onJoin {
                content
            }
        }
    }
}
VideoContentItemHolder.onClick() is a suspending function. Basically I am waiting for any of the itemHolder.onClick() to complete, and then returning the associated Content-object. I have attached the debugger to see that onClick() successfully completes for one of the itemHolders and I enter the onJoin-block, but the select clause never gets a result. So anyone waiting for the result is suspended indefinitely.
a

altavir

02/03/2019, 10:15 AM
What do you expect as result?
forEach
returns
Unit
m

madsbf

02/03/2019, 10:23 AM
I'm expecting a result of Content. I'm trying to select a deferred value. Like here: https://kotlinlang.org/docs/reference/coroutines/select-expression.html#selecting-deferred-values
I think the select-block is expecting Unit, so the forEach should be fine as long as I return a Content-object inside the onJoin-block. But maybe I'm misunderstanding something there?
a

altavir

02/03/2019, 10:25 AM
It is rather hard to see through it. Probably it is better to move launches from select.
m

madsbf

02/03/2019, 10:26 AM
👍 I'll try that
a

altavir

02/03/2019, 10:27 AM
Not sure it will help. But launching coroutines in select is bad practice anyway.
m

madsbf

02/03/2019, 10:30 AM
Hmm, I just tried creating the Jobs outside of the select-block. Unfortunately didn't make any difference 😞
Seems to be my lack of understanding of Scope. My current implementation waits for all Jobs to complete, not just one of them. If I replace launch with GlobalScope.launch f.x. it works. I'll have to look more into that to figure out how I should be handling this.
a

altavir

02/03/2019, 12:00 PM
coroutineScope
is not needed here, yet I don't understand why it behaves like this.
b

bdawg.io

02/04/2019, 8:58 AM
The
coroutineScope
is suspending until after all of your item holders have been clicked. If this isn't the intended behavior, cancel all of your other jobs in the onJoin:
Copy code
.onJoin {
    this@coroutineScope.cancelChildren()
    content
}
Your select clause is completing, but your
coroutineScope
won't return until all of the other launched jobs have completed. Thus preventing leaked jobs via Structured Concurrency
👍 1
m

madsbf

02/04/2019, 1:03 PM
Makes sense, thanks @bdawg.io 🙂
3 Views