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

gotoOla

03/12/2020, 1:32 PM
Hi! I have a class which looks like this
Copy code
class MyQueueProcessor: CoroutineScope by CouroutineScope(<http://Dispatchers.IO|Dispatchers.IO>) {
    suspend fun start() {
        pollMessages()
        processors.addAll(
            (1..5).map {
                launchMessageProcessor()
            }
        )
    }
    
    suspend fun pollMessages() = launch {
       while(true) {
          val messages = //... get messages from a queue
          internalChannel.send(messages)
       }
    }
    
    suspend fun launchMessageProcessor() = launch {
        for (messages in internalChannel) {
            // process each 'messages'
        }
    }

}
but for both pollMessages and launchMessageProcessor I get "Ambiguous coroutineContext due to CoroutineScope receiver of suspend function". How should I interpret this? Is it because suspend fun start() is public and you inherit the coroutineContext from the caller? Since I extend CoroutineScope, the launch and async stuff I use should run on that scope with that dispatcher (IO) right?
d

dekans

03/12/2020, 2:06 PM
suspend fun launchMessageProcessor() = launch {}
doesn't make sense.
launch
is not a suspend function
Either you remove the
suspend
keyword
e

Evan R.

03/12/2020, 2:06 PM
It is because if someone else is invoking the class functions from their own coroutine scope, it is not clear if the
launch
should occur in the caller’s coroutine scope or the coroutine scope of the class
d

dekans

03/12/2020, 2:07 PM
Or you remove the
launch
and
launchMessageProcessor
becomes a real suspend function
which will have to be started from inside a
launch {..}
idem for
pollMessages()
g

gotoOla

03/12/2020, 7:17 PM
@dekans ah of course, that's totally unecessary @Evan R. ah gotcha.
= this.launch {...}
should clarify that ambigouity if I remove the suspend from the function then, right?
e

Evan R.

03/12/2020, 7:17 PM
Yep!
g

gotoOla

03/12/2020, 10:15 PM
Thanks! 😊
6 Views