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

  • Learning Concurrency in Kotlin
  • Miguel Angel Castiblanco Torres
  • 169字
  • 2021-08-05 10:46:52

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.
主站蜘蛛池模板: 吉水县| 珲春市| 英吉沙县| 伊春市| 连山| 芦山县| 阿拉善左旗| 肥城市| 临夏市| 夏邑县| 江城| 青浦区| 南康市| 巧家县| 永登县| 图片| 东乌珠穆沁旗| 天全县| 乐山市| 安塞县| 白山市| 绥宁县| 广东省| 宾阳县| 吉首市| 长乐市| 安仁县| 五家渠市| 湖州市| 剑河县| 南木林县| 阜康市| 遵义市| 东安县| 磴口县| 天祝| 巫溪县| 舞阳县| 崇义县| 杭锦旗| 榕江县|