- 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.
推薦閱讀
- Learning Cython Programming(Second Edition)
- Learning C++ Functional Programming
- 你必須知道的204個Visual C++開發問題
- 微信小程序開發解析
- Mastering Ext JS
- UI設計基礎培訓教程(全彩版)
- 微信小程序開發邊做邊學(微課視頻版)
- 計算機程序的構造和解釋(JavaScript版)
- Learning TypeScript
- Mastering Unity 2017 Game Development with C#(Second Edition)
- Python 3.8編程快速入門
- Getting Started with SQL Server 2014 Administration
- TensorFlow+Keras深度學習算法原理與編程實戰
- 可信軟件基礎研究
- Visual C++.NET 2010開發實踐:基于C++/CLI