- 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.
推薦閱讀
- GAE編程指南
- Mastering Adobe Captivate 2017(Fourth Edition)
- HBase從入門到實戰(zhàn)
- PHP 編程從入門到實踐
- Swift 3 New Features
- 人臉識別原理及算法:動態(tài)人臉識別系統(tǒng)研究
- 軟件品質(zhì)之完美管理:實戰(zhàn)經(jīng)典
- Mastering C++ Multithreading
- IoT Projects with Bluetooth Low Energy
- Tableau Desktop可視化高級應用
- 大數(shù)據(jù)時代的企業(yè)升級之道(全3冊)
- STM8實戰(zhàn)
- Solr權(quán)威指南(下卷)
- Software Architecture with Python
- Parallel Programming with Python