[英]Coroutine's parent child relationship, getting a particular child and cancelling it?
I've this following suspend function我有这个以下暂停 function
override suspend fun getStories(type: Int) {
val job: Job = coroutineScope {
launch {
delay(20000)
}
launch {
delay(50000)
}
}
}
As per my understanding a coroutine Job
can have children, which in this case will be the two launch
coroutines.据我了解,协程
Job
可以有孩子,在这种情况下将是两个launch
协程。 My question is fairly simple.我的问题很简单。 How can I cancel the delay(50000) coroutine?
如何取消延迟(50000)协程?
I did run an iterator on job.children() method, but it was not fruitful.我确实在 job.children() 方法上运行了一个迭代器,但它没有成果。 Next I checked if a job has a get method for it's children.
接下来我检查了一个工作是否有它的孩子的 get 方法。 ♂️
♂️
Lemme know if it's not possible, or what's the point of children if I can't access them to individually call cancel?让我知道这是否不可能,或者如果我无法访问他们单独调用取消,那么孩子的意义何在?
Actually job.children
does work.实际上
job.children
确实有效。 Maybe the problem is how, where or when you're calling it.也许问题在于您调用它的方式、地点或时间。 This code works for me:
这段代码对我有用:
fun main() = runBlocking {
val job: Job = launch {
launch {
println("First job started")
delay(3000)
println("First job finished")
}.invokeOnCompletion {
println("First job completed!")
}
launch {
println("Second job started")
delay(4000)
println("Second job finished")
}.invokeOnCompletion {
println("Second job completed!")
}
launch {
println("Third job started")
delay(5000)
println("Third job finished")
}.invokeOnCompletion {
println("Third job completed!")
}
}
delay(1000)
job.children.elementAt(2).cancel()
delay(750)
job.children.elementAt(0).cancel()
delay(500)
job.children.elementAt(0).cancel()
}
This is the output:这是 output:
First job started
Second job started
Third job started
Third job completed!
First job completed!
Second job completed!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.