如何从外部调用按顺序制作协程运行

How to make coroutines run in sequence from outside call

我是协程及其工作原理方面的新手,我已经阅读了很多相关内容,但我似乎无法理解如何或是否可以实现我的最终目标。

我会尽可能详细地解释。无论如何,这是我的目标:

Ensure that coroutines run sequentially when a method that has said coroutine is called.

我创建了一个符合我希望发生的测试:

class TestCoroutines {

  @Test
  fun test() {
    println("Starting...")

    runSequentially("A")
    runSequentially("B")

    Thread.sleep(1000)
  }

  fun runSequentially(testCase: String) {
    GlobalScope.launch {
      println("Running test $testCase")
      println("Test $testCase ended")
    }
  }
}

重要说明:我无法控制某人调用 runSequentially 函数的次数。但是我要保证会按顺序调用。

此测试 运行s 以下输出:

Starting...
Running test B
Running test A
Test A ended
Test B ended

Starting...
Running test A
Running test B
Test B ended
Test A ended

This is the output I want to achieve :
Starting...     
Running test A
Test A ended
Running test B
Test B ended

我想我明白为什么会这样:每次我调用 runSequentially 时,我都在创建一个新的作业,它在 运行ning 的位置,并且 运行s 是异步的.

是否有可能使用协程来保证它们只会在前一个(如果是 运行ning)完成后 运行 完成,而我们无法控制所述协程的次数叫什么?

您正在寻找的是对请求进行排序的队列和为请求提供服务的工作人员的组合。总之,你需要一个 actor:

private val testCaseChannel = GlobalScope.actor<String>(
        capacity = Channel.UNLIMITED
) {
    for (testCase in channel) {
        println("Running test $testCase")
        println("Test $testCase ended")
    }
}

fun runSequentially(testCase: String) = testCaseChannel.sendBlocking(testCase)