taer
06/02/2020, 10:58 PMrunBlocking
with great results. But, now I want to use a scope for the class. I have this:
private val scope = CoroutineScope(serverCoroutineDispatcher )
fun doWork() {
runBlocking(scope.coroutineContext) {
//.....
}
}
The runBlocking with the scope's context feels wrong. I could scope.launch
but then it would return instantly. What am I missing?octylFractal
06/02/2020, 11:16 PMrunBlocking(ctx.newCoroutineContext(Job(ctx.coroutineContext[Job])))
basically, create a "child" of the contextrunBlocking
already creates a child coroutine, at least from static analysis. I'll test it outhenrikhorbovyi
06/02/2020, 11:21 PMscope.launch {
// your stuff
}
inside your doWork
function it will return instantly (as you noticed) because your function is not suspend or it is not waiting your launch to be completedrunBlocking(scope.coroutineContext) {
//.....
}
It causes an illusion that doWork is waiting for your process to be completed cause runBlocking blocks your current threadoctylFractal
06/02/2020, 11:28 PMrunBlocking
spawning a child job:
val ctx = CoroutineScope(Dispatchers.Default + SupervisorJob())
fun main() {
try {
runBlocking(ctx.coroutineContext) {
println("I am running...")
println("But now I will cancel the job by throwing! If I'm not a child coroutine, this _will_ cancel the ctx")
error("Test error")
}
} catch (e: Exception) {
println("The other runBlocking bailed out: ${e.message}")
}
runBlocking(ctx.coroutineContext) {
println("[A] I will never run if my Job is cancelled.")
}
// explicitly cancel now
ctx.coroutineContext.cancel()
runBlocking(ctx.coroutineContext) {
println("[B] I will never run if my Job is cancelled.")
}
}
results in
I am running...
But now I will cancel the job by throwing! If I'm not a child coroutine, this _will_ cancel the ctx
The other runBlocking bailed out: Test error
[A] I will never run if my Job is cancelled.
Exception in thread "main" kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelled}@3e57cd70
Luis Munoz
06/03/2020, 2:48 AMsuspend fun disconnect(reason: DisconnectReason) {
withContext(coroutineContext){
agentConnection.send(Frame().setCommand(Frame.Command.DISCONNECT))
agentConnection.close(reason)
}
}
taer
06/03/2020, 2:25 PMCoroutineScope(serverCoroutineDispatcher)
it creates a Job as part of that if there isn't one already. Then when I runBlocking with that scope that then throws, shouldn't the Job be canceled in that case?