- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 206字
- 2021-08-05 10:46:52
Active
A job in the state new can be started in many ways, but commonly it will be done by calling start() or join(), the difference being that the former will start the job without waiting for it to complete, whereas the latter will suspend execution until the job completes. Take this example into consideration:
fun main(args: Array<String>) {
val job = launch(start = CoroutineStart.LAZY) {
delay(3000)
}
job.start()
}
The mentioned code will not suspend execution when job.start() is invoked, so the application will complete its execution without waiting for job to complete.
Since start() doesn't suspend execution, it doesn't need to be called from a suspending function or coroutine. It can be called from any part of our application.
If we use join(),we will force the application to wait for job to complete, as demonstrated:
fun main(args: Array<String>) = runBlocking {
val job = launch(start = CoroutineStart.LAZY) {
delay(3000)
}
job.join()
}
As join() can suspend execution, it needs to be called from a coroutine or a suspending function. Note that runBlocking() is being used for that.
Any job that has been started is therefore active, and it will be active until it completes execution or until cancellation is requested.
推薦閱讀
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- Learning Java Functional Programming
- 計算機圖形學編程(使用OpenGL和C++)(第2版)
- 程序員數學:用Python學透線性代數和微積分
- OpenCV for Secret Agents
- 網頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- MySQL數據庫基礎實例教程(微課版)
- Android開發案例教程與項目實戰(在線實驗+在線自測)
- 21天學通C++(第5版)
- Mastering Gephi Network Visualization
- 大數據時代的企業升級之道(全3冊)
- Python Web自動化測試設計與實現
- H5+移動營銷設計寶典
- R的極客理想:量化投資篇
- Getting Started with the Lazarus IDE