目录

组合挂起函数

本节介绍了将挂起函数组合的各种方法。

默认顺序调用

假设我们在不同的地方定义了两个进行某种调用远程服务或者进行计算的挂起函数。我们只假设它们都是有用的,但是实际上它们在这个示例中只是为了该目的而延迟了一秒钟:

1. suspend fun doSomethingUsefulOne(): Int {
2. delay(1000L) // 假设我们在这里做了一些有用的事
3. return 13
4. }

6. suspend fun doSomethingUsefulTwo(): Int {
7. delay(1000L) // 假设我们在这里也做了一些有用的事
8. return 29
9. }

如果需要按 顺序 调用它们,我们接下来会做什么——首先调用 doSomethingUsefulOne 接下来 调用 doSomethingUsefulTwo,并且计算它们结果的和吗? 实际上,如果我们要根据第一个函数的结果来决定是否我们需要调用第二个函数或者决定如何调用它时,我们就会这样做。

我们使用普通的顺序来进行调用,因为这些代码是运行在协程中的,只要像常规的代码一样 顺序 都是默认的。下面的示例展示了测量执行两个挂起函数所需要的总时间:

1. import kotlinx.coroutines.*
2. import kotlin.system.*

4. fun main() = runBlocking<Unit> {
5. //sampleStart
6. val time = measureTimeMillis {
7. val one = doSomethingUsefulOne()
8. val two = doSomethingUsefulTwo()
9. println("The answer is ${one + two}")
10. }
11. println("Completed in $time ms")
12. //sampleEnd
13. }

15. suspend fun doSomethingUsefulOne(): Int {
16. delay(1000L) // 假设我们在这里做了些有用的事
17. return 13
18. }

20. suspend fun doSomethingUsefulTwo(): Int {
21. delay(1000L) // 假设我们在这里也做了一些有用的事
22. return 29
23. }

可以在这里获取完整代码。

它的打印输出如下:

1. The answer is 42
2. Completed in 2017 ms

使用 async 并发

如果 doSomethingUsefulOne 与 doSomethingUsefulTwo 之间没有依赖,并且我们想更快的得到结果,让它们进行 并发 吗?这就是 async 可以帮助我们的地方。

在概念上,async 就类似于 launch。它启动了一个单独的协程,这是一个轻量级的线程并与其它所有的协程一起并发的工作。不同之处在于 launch 返回一个 Job 并且不附带任何结果值,而 async 返回一个 Deferred —— 一个轻量级的非阻塞 future, 这代表了一个将会在稍后提供结果的 promise。你可以使用 .await() 在一个延期的值上得到它的最终结果, 但是 Deferred 也是一个 Job,所以如果需要的话,你可以取消它。

1. import kotlinx.coroutines.*
2. import kotlin.system.*

4. fun main() = runBlocking<Unit> {
5. //sampleStart
6. val time = measureTimeMillis {
7. val one = async { doSomethingUsefulOne() }
8. val two = async { doSomethingUsefulTwo() }
9. println("The answer is ${one.await() + two.await()}")
10. }
11. println("Completed in $time ms")
12. //sampleEnd
13. }

15. suspend fun doSomethingUsefulOne(): Int {
16. delay(1000L) // 假设我们在这里做了些有用的事
17. return 13
18. }

20. suspend fun doSomethingUsefulTwo(): Int {
21. delay(1000L) // 假设我们在这里也做了些有用的事
22. return 29
23. }

可以在这里获取完整代码。

它的打印输出如下:

1. The answer is 42
2. Completed in 1017 ms

这里快了两倍,因为两个协程并发执行。 请注意,使用协程进行并发总是显式的。

惰性启动的 async

可选的,async 可以通过将 start 参数设置为 CoroutineStart.LAZY 而变为惰性的。 在这个模式下,只有结果通过 await 获取的时候协程才会启动,或者在 Job 的 start 函数调用的时候。运行下面的示例:

1. import kotlinx.coroutines.*
2. import kotlin.system.*

4. fun main() = runBlocking<Unit> {
5. //sampleStart
6. val time = measureTimeMillis {
7. val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() }
8. val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() }
9. // 执行一些计算
10. one.start() // 启动第一个
11. two.start() // 启动第二个
12. println("The answer is ${one.await() + two.await()}")
13. }
14. println("Completed in $time ms")
15. //sampleEnd
16. }

18. suspend fun doSomethingUsefulOne(): Int {
19. delay(1000L) // 假设我们在这里做了些有用的事
20. return 13
21. }

23. suspend fun doSomethingUsefulTwo(): Int {
24. delay(1000L) // 假设我们在这里也做了些有用的事
25. return 29
26. }

可以在这里获取完整代码。

它的打印输出如下:

1. The answer is 42
2. Completed in 1017 ms

因此,在先前的例子中这里定义的两个协程没有执行,但是控制权在于程序员准确的在开始执行时调用 start。我们首先 调用 one,然后调用 two,接下来等待这个协程执行完毕。

注意,如果我们只是在 println 中调用 await,而没有在单独的协程中调用 start,这将会导致顺序行为,直到 await 启动该协程 执行并等待至它结束,这并不是惰性的预期用例。 在计算一个值涉及挂起函数时,这个 async(start = CoroutineStart.LAZY) 的用例用于替代标准库中的 lazy 函数。

async 风格的函数

我们可以定义异步风格的函数来 异步 的调用 doSomethingUsefulOne 和 doSomethingUsefulTwo 并使用 async 协程建造器并带有一个显式的 GlobalScope 引用。 我们给这样的函数的名称中加上“……Async”后缀来突出表明:事实上,它们只做异步计算并且需要使用延期的值来获得结果。

1. // somethingUsefulOneAsync 函数的返回值类型是 Deferred<Int>
2. fun somethingUsefulOneAsync() = GlobalScope.async {
3. doSomethingUsefulOne()
4. }

6. // somethingUsefulTwoAsync 函数的返回值类型是 Deferred<Int>
7. fun somethingUsefulTwoAsync() = GlobalScope.async {
8. doSomethingUsefulTwo()
9. }

注意,这些 xxxAsync 函数不是 挂起 函数。它们可以在任何地方使用。 然而,它们总是在调用它们的代码中意味着异步(这里的意思是 并发 )执行。

下面的例子展示了它们在协程的外面是如何使用的:

1. import kotlinx.coroutines.*
2. import kotlin.system.*

4. //sampleStart
5. // 注意,在这个示例中我们在 `main` 函数的右边没有加上 `runBlocking`
6. fun main() {
7. val time = measureTimeMillis {
8. // 我们可以在协程外面启动异步执行
9. val one = somethingUsefulOneAsync()
10. val two = somethingUsefulTwoAsync()
11. // 但是等待结果必须调用其它的挂起或者阻塞
12. // 当我们等待结果的时候,这里我们使用 `runBlocking { …… }` 来阻塞主线程
13. runBlocking {
14. println("The answer is ${one.await() + two.await()}")
15. }
16. }
17. println("Completed in $time ms")
18. }
19. //sampleEnd

21. fun somethingUsefulOneAsync() = GlobalScope.async {
22. doSomethingUsefulOne()
23. }

25. fun somethingUsefulTwoAsync() = GlobalScope.async {
26. doSomethingUsefulTwo()
27. }

29. suspend fun doSomethingUsefulOne(): Int {
30. delay(1000L) // 假设我们在这里做了些有用的事
31. return 13
32. }

34. suspend fun doSomethingUsefulTwo(): Int {
35. delay(1000L) // 假设我们在这里也做了些有用的事
36. return 29
37. }

可以在这里获取完整代码。

这种带有异步函数的编程风格仅供参考,因为这在其它编程语言中是一种受欢迎的风格。在 Kotlin 的协程中使用这种风格是强烈不推荐的, 原因如下所述。

考虑一下如果 val one = somethingUsefulOneAsync() 这一行和 one.await() 表达式这里在代码中有逻辑错误, 并且程序抛出了异常以及程序在操作的过程中中止,将会发生什么。 通常情况下,一个全局的异常处理者会捕获这个异常,将异常打印成日记并报告给开发者,但是反之该程序将会继续执行其它操作。但是这里我们的 somethingUsefulOneAsync 仍然在后台执行, 尽管如此,启动它的那次操作也会被终止。这个程序将不会进行结构化并发,如下一小节所示。

使用 async 的结构化并发

让我们使用使用 async 的并发这一小节的例子并且提取出一个函数并发的调用 doSomethingUsefulOne 与 doSomethingUsefulTwo 并且返回它们两个的结果之和。 由于 async 被定义为了 CoroutineScope 上的扩展,我们需要将它写在作用域内,并且这是 coroutineScope 函数所提供的:

1. suspend fun concurrentSum(): Int = coroutineScope {
2. val one = async { doSomethingUsefulOne() }
3. val two = async { doSomethingUsefulTwo() }
4. one.await() + two.await()
5. }

这种情况下,如果在 concurrentSum 函数内部发生了错误,并且它抛出了一个异常, 所有在作用域中启动的协程都会被取消。

1. import kotlinx.coroutines.*
2. import kotlin.system.*

4. fun main() = runBlocking<Unit> {
5. //sampleStart
6. val time = measureTimeMillis {
7. println("The answer is ${concurrentSum()}")
8. }
9. println("Completed in $time ms")
10. //sampleEnd
11. }

13. suspend fun concurrentSum(): Int = coroutineScope {
14. val one = async { doSomethingUsefulOne() }
15. val two = async { doSomethingUsefulTwo() }
16. one.await() + two.await()
17. }

19. suspend fun doSomethingUsefulOne(): Int {
20. delay(1000L) // 假设我们在这里做了些有用的事
21. return 13
22. }

24. suspend fun doSomethingUsefulTwo(): Int {
25. delay(1000L) // 假设我们在这里也做了些有用的事
26. return 29
27. }

可以在这里获取完整代码。

从上面的 main 函数的输出可以看出,我们仍然可以同时执行这两个操作:

1. The answer is 42
2. Completed in 1017 ms

取消始终通过协程的层次结构来进行传递:

1. import kotlinx.coroutines.*

3. fun main() = runBlocking<Unit> {
4. try {
5. failedConcurrentSum()
6. } catch(e: ArithmeticException) {
7. println("Computation failed with ArithmeticException")
8. }
9. }

11. suspend fun failedConcurrentSum(): Int = coroutineScope {
12. val one = async<Int> {
13. try {
14. delay(Long.MAX_VALUE) // 模拟一个长时间的运算
15. 42
16. } finally {
17. println("First child was cancelled")
18. }
19. }
20. val two = async<Int> {
21. println("Second child throws an exception")
22. throw ArithmeticException()
23. }
24. one.await() + two.await()
25. }

可以在这里获取完整代码。

请注意,如果其中一个子协程(即 two)失败,第一个 async 以及等待中的父协程都会被取消:

1. Second child throws an exception
2. First child was cancelled
3. Computation failed with ArithmeticException