官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 获嘉县| 调兵山市| 嘉祥县| 攀枝花市| 永定县| 孟州市| 额济纳旗| 永靖县| 平和县| 宜川县| 茶陵县| 赤城县| 新源县| 随州市| 都安| 襄樊市| 芮城县| 儋州市| 福建省| 民乐县| 乐山市| 榆中县| 八宿县| 永吉县| 贵港市| 全南县| 平陆县| 七台河市| 炎陵县| 济南市| 铜川市| 读书| 伊金霍洛旗| 黄龙县| 织金县| 新平| 万山特区| 千阳县| 菏泽市| 朝阳市| 都匀市|