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

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.

主站蜘蛛池模板: 会东县| 新宁县| 神农架林区| 阿克苏市| 新平| 云龙县| 康马县| 镇安县| 东辽县| 嘉祥县| 甘泉县| 勃利县| 永善县| 普格县| 尼勒克县| 墨江| 海林市| 特克斯县| 漳州市| 贞丰县| 石狮市| 鲁山县| 金川县| 迁西县| 灵丘县| 襄垣县| 澎湖县| 台安县| 克东县| 城市| 东光县| 长治县| 台湾省| 五家渠市| 凤冈县| 梅州市| 新昌县| 鞍山市| 和政县| 苍溪县| 鹤峰县|