1
votes

This doesn't have compilation error :

suspend fun test() {
    runBlocking {

    }
}

This has a compilation error :

suspend fun test() {
    launch {

    }
}

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public fun CoroutineScope.launch(context: CoroutineContext = ..., start: CoroutineStart = ..., block: suspend CoroutineScope.() -> Unit): Job defined in kotlinx.coroutines

I don't really understand what is the problem...

1
launch requires a scope whereas runBlocking is just a way to block a thread. So to resolve the error you have to use one of the coroutinescope to launch like GlobalScope.launch{} - Gautam

1 Answers

1
votes

Coroutines are launched with launch coroutine builder in a context of some CoroutineScope:

fun test() = CoroutineScope(Dispatchers.Main).launch {
}

launch - is an extension function on CoroutineScope object, it is defined like this:

public fun CoroutineScope.launch(...): Job {}

runBlocking - is not an extension function, so it can be called as a regular function, it is defined like this:

public fun <T> runBlocking(...): T {}