- 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.
推薦閱讀
- WildFly:New Features
- Mastering Zabbix(Second Edition)
- C#完全自學教程
- 編程卓越之道(卷3):軟件工程化
- Learning SAP Analytics Cloud
- DevOps Automation Cookbook
- Hands-On RESTful Web Services with Go
- Serverless Web Applications with React and Firebase
- Java RESTful Web Service實戰
- JavaScript前端開發基礎教程
- Python深度學習:基于PyTorch
- Learning IBM Bluemix
- Python自動化開發實戰
- 測試架構師修煉之道:從測試工程師到測試架構師(第2版)
- Unity3D高級編程:主程手記