Reputation: 2335
I'm learning Coroutines of Kotlin, I'm a beginner of running code online in https://try.kotlinlang.org/
I try to test Code A in the website, but I get many errors just like Image A, how can I fix it?
Code A
import kotlinx.coroutines.*
fun main(args: Array<String>) {
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
Upvotes: 1
Views: 1242
Reputation: 1449
Try to run following code:
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
fun main() = runBlocking<Unit> { //here i made change
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
Output would be :)
Cancelling child
Child is cancelled
Parent is not cancelled
Upvotes: 2