smit01
02/22/2022, 6:20 PMrunBlocking{
println("init")
launch{
delay(200)
println("launch one")
}
println("mid")
launch{
delay(100)
println("launch two")
}
println("end")
}
init
mid
end
launch two
launch one
suspend fun cli(arg:String)=Runtime.getRuntime() .exec(arg).getInputStream().bufferedReader().readLines().forEach(::println)
runBlocking{
println("init")
launch{
cli("du -hs")
println("launch one")
}
println("mid")
launch{
cli("ls")
println("launch two")
}
println("end")
}
//optput
init
mid
end
11G .
launch one
AR
UB
storage
launch two
In this code why in second runBlocking i am not getting output like mentioned below where du -hs takes more time compare to ls command. In first runBlocking launch one has 200 delay so first second launch runs but in second runBlocking it doesn't why? Sorry for noob question or queries but I am new to coroutines and trying to learn.
init
mid
end
AR
UB
storage
launch two
11G
launch oneJoffrey
02/22/2022, 7:09 PMcli()
calls are blocking calls, marking the function suspend
does not make it automatically non-blocking. Running the process and reading the input stream is blocking the only thread you're using (the one held by runBlocking
).
You can work around this by wrapping the body of cli()
in withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
so it's dispatched on another thread and blocks that thread instead of the one of runBlockingJoffrey
02/22/2022, 7:14 PMrunBlocking(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
smit01
02/24/2022, 5:58 AM