我已经上课和考试了。我想像单线程一样执行所有启动。附上示例实现和测试。测试一定是正确的。
class MainClass {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
var value = 0
fun run() {
scope.launch(Dispatchers.IO) {
delay(1000)
withContext(Dispatchers.Main) {
withContext(Dispatchers.IO) {
delay(1000)
withContext(Dispatchers.Main) {
value = 1
}
}
}
}
}
}
class TestTest {
@Test
fun test() = runTest {
val test = MainClass()
test.run()
assertTrue(test.value == 1)
}
}
运行一个新的协程并阻塞当前线程,直到它的 完成
@Test
fun test() = runTest {
val test = MainClass()
runBlocking{
test.run()
}
assertTrue(test.value == 1)
}