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

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.

主站蜘蛛池模板: 虹口区| 巴塘县| 观塘区| 龙泉市| 那曲县| 泾阳县| 英吉沙县| 静乐县| 昌邑市| 班戈县| 襄樊市| 临桂县| 平远县| 明水县| 绥棱县| 庆城县| 扬中市| 普兰店市| 依安县| 通辽市| 中西区| 孝感市| 灵石县| 五峰| 昭苏县| 确山县| 哈尔滨市| 民勤县| 栖霞市| 河北区| 石首市| 无为县| 曲阜市| 芮城县| 鹤峰县| 简阳市| 鹤岗市| 沾益县| 开原市| 新野县| 隆德县|