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

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.

主站蜘蛛池模板: 越西县| 南投市| 台东县| 潍坊市| 武城县| 宣恩县| 庆城县| 乌海市| 山东| 安塞县| 石棉县| 兰考县| 太湖县| 土默特右旗| 东海县| 神池县| 增城市| 阜平县| 项城市| 彝良县| 兴国县| 陵川县| 衡南县| 天祝| 遂昌县| 平塘县| 汾西县| 东平县| 清原| 当涂县| 巴东县| 神农架林区| 承德市| 吴江市| 台南市| 九江市| 信阳市| 滨州市| 尉氏县| 淮阳县| 临沂市|