- 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.
推薦閱讀
- .NET之美:.NET關鍵技術深入解析
- 自己動手實現Lua:虛擬機、編譯器和標準庫
- 軟件測試技術指南
- Learning ArcGIS for Desktop
- Microsoft 365 Certified Fundamentals MS-900 Exam Guide
- 運維前線:一線運維專家的運維方法、技巧與實踐
- Machine Learning for OpenCV
- 從零開始構建深度前饋神經網絡:Python+TensorFlow 2.x
- Python趣味創意編程
- Learning Zimbra Server Essentials
- Swift語言實戰晉級(第2版)
- 區塊鏈原理與技術應用
- Go Programming Cookbook(Second Edition)
- RPA開發:UiPath入門與實戰
- Elixir Cookbook