我有两个协程,我想检查它们是否在相同的上下文/调度程序中运行。这是我的问题的简化版本,但答案将适用于我正在做的事情:
@Test
fun test() {
val io = runBlocking(Dispatcher.IO) {
coroutineContext
}
val nonIo = runBlocking() {
coroutineContext
}
assertNotEquals(io, nonIo)
}
但是,这是一个糟糕的测试,因为我只是在比较两个不同的对象。我想比较一下他们是否使用 Dispatcher.IO
。
最佳答案
我想你的意思是问协程是否使用相同的 Dispatcher,对吧?调度程序只是 CoroutineContext 的一部分。您可以使用带有键 ContinuationInterceptor
的 CoroutineContext 的 get
函数来检索 Dispatcher。
val io = withContext(Dispatchers.IO) {
coroutineContext[ContinuationInterceptor]
}
val nonIo = withContext(Dispatchers.Default) {
coroutineContext[ContinuationInterceptor]
}
assertNotEquals(io, nonIo)
关于android - 如何检查协程是否使用相同的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63383073/