如何 运行 并行执行两个作业但等待另一个作业完成使用 kotlin 协程

How to run two jobs in parallel but wait for another job to finish using kotlin coroutines

我有以下工作:

  1. 异步扩展复杂的日历视图
  2. 正在下载事件 A
  3. 正在下载事件 B
  4. 将日历视图添加到它的父级
  5. 将 A 事件添加到日历中
  6. 将 B 事件添加到日历中

我要

我试过 async await 但它使它们同时完成(如预期的那样)。我认为这个示例可能是学习并行编程概念的好方法,例如信号量互斥锁或自旋锁。但是太复杂了我看不懂。

我应该如何使用 Kotlin 协程来实现这些?

这很简单。您需要做的就是:

  1. 实施 CoroutineScope 并创建 CoroutineContext,或使用 GlobalScope
  2. 使用本地 CoroutineScopeGlobalScope.launch() 启动协程。
  3. 在协程中使用async/await到run/wait的异步操作。

您可以将下一个代码应用于您的算法(所有解释都在评论中):

class SomeClass : CoroutineScope {
    private var job: Job = Job()

    // creating local CoroutineContext
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    // cancel the Job if it is no longer needed
    fun onClear() {
        job.cancel()
    }

    fun doJob() {
        // launch coroutine
        launch {
            // run Job1, Job2, Job3 in parallel, asyncIO - is an extension function on CoroutineScope
            val d1 = asyncIO { job1() }
            val d2 = asyncIO { job2() }
            val d3 = asyncIO { job3() }

            // waiting for result of Job1
            val job1Result = d1.await()

            // run Job4
            val d4 = asyncIO { job4(job1Result) }

            // waiting for result of Job2 and Job4
            val job2Result = d2.await()
            val job4Result = d4.await()

            // run Job5
            val d5 = asyncIO { job5(job2Result, job4Result) }

            // waiting for result of Job3
            val job3Result = d3.await()

            // run Job6
            val d6 = asyncIO { job6(job3Result, job4Result) }

            onDone(d5.await(), d6.await())
        }
    }

    private fun onDone(job5Result: String, job6Result: String) {
        // do something with result of Job5 and Job6
    }


    fun job1(): String {
        return "Result of job1"
    }

    fun job2(): String {
        return "Result of job2"
    }

    fun job3(): String {
        return "Result of job3"
    }

    fun job4(job1Result: String): String {
        return "Result of job4"
    }

    fun job5(job2Result: String, job4Result: String): String {
        return "Result of job5"
    }

    fun job6(job3Result: String, job4Result: String): String {
        return "Result of job6"
    }

    // extension function
    fun <T> CoroutineScope.asyncIO(ioFun: () -> T) = async(Dispatchers.IO) { ioFun() }
}