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

Sachin Maharana

10/22/2020, 12:10 PM
I am not sure what i am doing wrong here. Can anybody point out the obvious. 😅
Copy code
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
import kotlinx.coroutines.delay

fun main() = runBlocking {
    println("${Thread.activeCount()} threads active at the start")
    val time = measureTimeMillis {
        createCoroutines(10_000)
    }
    println("${Thread.activeCount()} threads active at the end")
    println("Took $time ms")
}

suspend fun createCoroutines(amount: Int) {
    val jobs = ArrayList<Job>()
    for (i in 1..amount) {
        jobs += launch {
            delay(1000)
        }
    }
    jobs.forEach {
        it.join()
    }
}
w

william

10/22/2020, 12:11 PM
what is your error / problem?
2
b

bezrukov

10/22/2020, 12:14 PM
you're probably about unknown
launch
, right?
launch
is a CoroutineScope's extension, so you need a scope to call it. Here is an idiomatic way to write this:
Copy code
fun main() = runBlocking {
    println("${Thread.activeCount()} threads active at the start")
    val time = measureTimeMillis {
        createCoroutines(10_000)
    }
    println("${Thread.activeCount()} threads active at the end")
    println("Took $time ms")
}

suspend fun createCoroutines(amount: Int) = coroutineScope {
    for (i in 1..amount) {
        launch {
            delay(1000)
        }
    }
}
👍 1
s

Sachin Maharana

10/22/2020, 12:14 PM
ahh..sorry i thought i made some stupid mistake. error is this.
Copy code
e: /home/test/IdeaProjects/Coroutines/src/main/kotlin/main.kt: (29, 17): Unresolved reference: launch
@bezrukov Yes. that works.Thanks. But i assumed, if i am using runBLocking in main , doesn't that gives scope to the createCoroutine function. and consequently launch could have been called without reference error?
Also, is there a difference between runBlocking scope and coroutineScope?
b

bezrukov

10/22/2020, 12:23 PM
But i assumed, if i am using runBLocking in main , doesn't that gives scope to the createCoroutine function.
No, to have a CoroutineScope as a receiver type for
createCoroutines
you need explicitly write it:
fun CoroutineScope.createCoroutines(amount....
but it is not recommended way. Without it, where the compiler should take a scope, if you call this function from outside of
runBlocking
?
Also, is there a difference between runBlocking scope and coroutineScope?
yes, runBlocking can be called from non-suspending fun, while coroutineScope can be only called from
suspend
fun.
👍 1
2 Views