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

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.
主站蜘蛛池模板: 丹巴县| 柳州市| 海门市| 西林县| 海城市| 扎囊县| 承德县| 宁陵县| 南溪县| 山阳县| 三门县| 余姚市| 贵州省| 交口县| 台州市| 东乡县| 孟州市| 广丰县| 公安县| 巴东县| 诸城市| 南部县| 萨迦县| 荣成市| 平昌县| 麻阳| 鲜城| 鲜城| 平果县| 资兴市| 南和县| 开阳县| 固镇县| 云林县| 湄潭县| 宁德市| 阿克陶县| 宜州市| 芮城县| 兴仁县| 平陆县|