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

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.

主站蜘蛛池模板: 安泽县| 社旗县| 沾益县| 巴林左旗| 佳木斯市| 宁明县| 盐山县| 垫江县| 澄江县| 正镶白旗| 民勤县| 吐鲁番市| 枣庄市| 肥西县| 原平市| 珲春市| 会昌县| 项城市| 嘉鱼县| 宁安市| 镶黄旗| 本溪| 玛纳斯县| 象州县| 彰武县| 民和| 朝阳市| 新邵县| 白玉县| 罗田县| 尖扎县| 财经| 三都| 台州市| 汝南县| 阜阳市| 长泰县| 建阳市| 吴桥县| 怀安县| 长子县|