Hasan
05/10/2020, 9:13 PMfun asyncOp(nums: List<Int>, mult: Int, id: String) = GlobalScope.async {
println("1 - $id: $mult times list computing asynchronously")
Thread.sleep(2000L * mult)
println("2 - $id: $mult times list computing asynchronously")
Thread.sleep(1000L * mult)
nums.map { it * mult }
}
suspend fun main() {
val nums = listOf(1,2,3,4,5,6)
val double = asyncOp(nums, 2,"first")
val triple = asyncOp(nums, 3,"second")
println("Double requested: $double")
println("Triple requested: $triple")
println("Waiting...")
println(awaitAll(triple, double))
}
This works as intended, but Intellij suggested this instead:
suspend fun asyncOp(nums: List<Int>, mult: Int, id: String) =
withContext(Dispatchers.Default) {
println("1 - $id: $mult times list computing asynchronously")
Thread.sleep(2000L * mult)
println("2 - $id: $mult times list computing asynchronously")
Thread.sleep(1000L * mult)
nums.map { it * mult }
}
But this runs it in a blocking way which is not what I wanted.
What do you guys think? Where might I be going wrong?octylFractal
05/10/2020, 9:14 PMdelay
instead of Thread.sleep
, delay
is suspendingsuspend fun op(nums: List<Int>, mult: Int, id: String): List<Int> {
println("1 - $id: $mult times list computing asynchronously")
delay(2000L * mult)
println("2 - $id: $mult times list computing asynchronously")
delay(1000L * mult)
return nums.map { it * mult }
}
suspend fun main() {
val nums = listOf(1, 2, 3, 4, 5, 6)
coroutineScope {
val double = async { op(nums, 2, "first") }
val triple = async { op(nums, 3, "second") }
println("Double requested: $double")
println("Triple requested: $triple")
println("Waiting...")
println(awaitAll(triple, double))
}
}
Hasan
05/10/2020, 9:28 PMmain
, does that run in a blocking way in your example?octylFractal
05/10/2020, 9:29 PMHasan
05/10/2020, 9:32 PMcoroutineScope
finishes?octylFractal
05/10/2020, 9:32 PMHasan
05/10/2020, 9:33 PMGlobalScope
not right?octylFractal
05/10/2020, 9:51 PMcoroutineContext[Job]!!.cancel()
in main()
from our example, after starting the two async ops: in your example they would still proceed to do the nums.map
code, where as in my code, they immediately stop after resuming from delay (or potentially sooner, don't recall when cancellation is detected by delay
)Hasan
05/10/2020, 10:20 PM