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

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.

主站蜘蛛池模板: 岱山县| 诸暨市| 宁德市| 博客| 昌邑市| 许昌县| 彰化市| 呼和浩特市| 肇东市| 清远市| 清河县| 昌邑市| 平顶山市| 雷山县| 双牌县| 全椒县| 天峨县| 拜泉县| 兴海县| 昆山市| 承德县| 天峻县| 青浦区| 渭源县| 天台县| 叶城县| 长汀县| 山丹县| 平和县| 当涂县| 信丰县| 乐至县| 瑞昌市| 卢氏县| 南靖县| 黄冈市| 荔浦县| 行唐县| 澄城县| 饶阳县| 枞阳县|