- 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.
推薦閱讀
- TypeScript Blueprints
- C語言程序設(shè)計(jì)(第2版)
- Python自動(dòng)化運(yùn)維快速入門
- NumPy Essentials
- Haxe Game Development Essentials
- Angular開發(fā)入門與實(shí)戰(zhàn)
- C#程序設(shè)計(jì)教程(第3版)
- C++20高級(jí)編程
- Mastering ArcGIS Enterprise Administration
- 編寫高質(zhì)量代碼:改善Objective-C程序的61個(gè)建議
- PHP編程基礎(chǔ)與實(shí)踐教程
- Python Interviews
- SwiftUI極簡開發(fā)
- 深度學(xué)習(xí)程序設(shè)計(jì)實(shí)戰(zhàn)
- JavaScript Unit Testing