Ofek Ron
Ofek Ron

Reputation: 8580

Confused about Kotlin Coroutines

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...

Upvotes: 1

Views: 4781

Answers (1)

Sergio
Sergio

Reputation: 30635

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 {}

Upvotes: 4

Related Questions