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

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.
主站蜘蛛池模板: 封开县| 宝清县| 晋中市| 安多县| 深州市| 临邑县| 贡嘎县| 三江| 延川县| 仙桃市| 沙河市| 渝中区| 延庆县| 应城市| 鸡西市| 阜平县| 钟山县| 赤峰市| 上杭县| 广昌县| 开鲁县| 阳信县| 滨州市| 翁牛特旗| 和硕县| 砀山县| 剑阁县| 栖霞市| 桐城市| 鄱阳县| 乐安县| 崇左市| 百色市| 浦东新区| 平南县| 两当县| 孟村| 湘潭县| 衡阳县| 剑川县| 延川县|