Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

kotlin - Ambiguous coroutineContext while calling co-routine builders (launch, async) in a suspended function

I have a class Runner that implements the CoroutineScope interface as shown below. It has a suspended function called run. when I use the co-routine builder functions (launch, async) in this suspended run function I get the below warning

Ambiguous coroutineContext due to CoroutineScope receiver of suspend function

The Runner class has a single coroutineContext property implemented. Can someone explain the logic behind the warning message?

class Runner: CoroutineScope {

    override private val coroutineContext = Dispatchers.IO

    suspend fun run()  {
           val job1 = launch { delay(2000); println("launching job1") }
           val job2 = launch { delay(2000); println("launching job2") }
           listOf(job1, job2).forEach { it.join() }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

it is ambiguous due to the suspend modifier. Your run() function will be called from another couroutineScope. So the launch builders inside it can start a coroutine or suspend within an existing coroutine. That is the ambiguity. You can fix it by removing the suspend modifier:

class Runner : CoroutineScope {

    override val coroutineContext = Dispatchers.IO

    fun run() = launch {
            val job1 = launch { delay(2000); println("launching job1") }
            val job2 = launch { delay(2000); println("launching job2") }
            listOf(job1, job2).forEach { it.join() }
        }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...