官术网_书友最值得收藏!

Canceling

An active job that is requested to be cancelled may enter a staging state called canceling. To request a job to cancel its execution, the cancel() function should be called:

fun main(args: Array<String>) = runBlocking {
val job = launch {
// Do some work here
delay(5000)
}

delay(2000)
job.cancel()
}

Here, the execution of the job will be cancelled after 2 seconds; cancel() has an optional cause parameter. If an exception is the cause of the cancellation, it's a good practice to send it there; that way, it can be retrieved at a later time:

fun main(args: Array<String>) = runBlocking {
val job = launch {
// Do some work here
delay(5000)
}

delay(2000)

// cancel with a cause
job.cancel(cause = Exception("Timeout!"))
}

There is also a cancelAndJoin() function. As its name suggests, this will not only cancel the execution but also suspend the current coroutine until the cancellation has been completed.

Currently, there is no implementation of cancelAndJoin() that allows a cause to be passed.
主站蜘蛛池模板: 神木县| 洪洞县| 汽车| 江华| 长葛市| 盖州市| 正阳县| 铅山县| 康定县| 沛县| 嘉荫县| 潞西市| 故城县| 合江县| 武清区| 怀远县| 丰顺县| 太白县| 永丰县| 扶余县| 如东县| 镇原县| 申扎县| 射洪县| 吴川市| 麦盖提县| 石柱| 江安县| 湘阴县| 安徽省| 卢湾区| 阿坝| 年辖:市辖区| 兴宁市| 花莲市| 灌阳县| 顺义区| 宜州市| 莎车县| 太康县| 武汉市|