- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 193字
- 2021-08-05 10:46:45
Coroutine builders
A coroutine builder is a function that takes a suspending lambda and creates a coroutine to run it. Kotlin provides many coroutine builders that adjust to many different common scenarios, such as:
- async(): Used to start a coroutine when a result is expected. It has to be used with caution because async() will capture any exception happening inside the coroutine and put it in its result. Returns a Deferred<T> that contains either the result or the exception.
- launch(): Starts a coroutine that doesn't return a result. Returns a Job that can be used to cancel its execution or the execution of its children.
- runBlocking(): Created to bridge blocking code into suspendable code. It's commonly used in main() methods and unit tests. runBlocking() blocks the current thread until the execution of the coroutine is completed.
Here is an example of async():
val result = async {
isPalindrome(word = "Sample")
}
result.await()
In this example, async() is executed in the default dispatcher. It is possible to manually specify the dispatcher:
val result = async(Unconfined) {
isPalindrome(word = "Sample")
}
result.await()
In this second example, Unconfined is used as the dispatcher of the coroutine.
推薦閱讀
- scikit-learn Cookbook
- 嵌入式軟件系統測試:基于形式化方法的自動化測試解決方案
- TypeScript圖形渲染實戰:基于WebGL的3D架構與實現
- Eclipse Plug-in Development:Beginner's Guide(Second Edition)
- Python數據挖掘與機器學習實戰
- 用Python實現深度學習框架
- Learn React with TypeScript 3
- ASP.NET開發與應用教程
- Azure Serverless Computing Cookbook
- Developing SSRS Reports for Dynamics AX
- JavaScript程序設計(第2版)
- Java Web從入門到精通(第3版)
- Python預測之美:數據分析與算法實戰(雙色)
- Python編程基礎教程
- 現代C++語言核心特性解析