我有下面的代码,并故意触发一个要被errorHandler捕获的异常
private var coroutineScope: CoroutineScope? = null
private val mainThreadSurrogate = newSingleThreadContext("Test Main")
@Before
fun setUp() {
Dispatchers.setMain(mainThreadSurrogate)
}
@After
fun tearDown() {
// reset main dispatcher to the original Main dispatcher
Dispatchers.resetMain()
mainThreadSurrogate.close()
}
private val errorHandler = CoroutineExceptionHandler { context, error ->
println("Launch Exception ${Thread.currentThread()}")
coroutineScope?.launch(Dispatchers.Main) {
println("Launch Exception Result ${Thread.currentThread()}")
}
}
@Test
fun testData() {
runBlocking {
coroutineScope = MainScope()
coroutineScope?.launch(errorHandler) {
println("Launch Fetch Started ${Thread.currentThread()}")
throw IllegalStateException("error")
}?.join()
}
}这将导致
Launch Fetch Started Thread[Test Main @coroutine#2,5,main]
Launch Exception Thread[Test Main @coroutine#2,5,main]
Launch Exception Result Thread[Test Main @coroutine#3,5,main]如果我将coroutineScope = MainScope()改为
coroutineScope = CoroutineScope(Dispatchers.Main)coroutineScope = CoroutineScope(Dispatchers.IO)coroutineScope?.launch(Dispatchers.Main) {...}不会运行,也就是说,Launch Exception Result ...不会被打印。
为什么会这样呢?
发布于 2021-01-02 07:22:58
显然,我们需要使用SupervisorJob()创建一个作用域,以便父作业不受子作业崩溃的影响。
coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)注意,MainScope()是CoroutineScope(SupervisorJob() + Dispatchers.Main)。
正如SupervisorJob中提到的
子任务的失败或取消不会导致主管作业失败,也不会影响其其他子任务,因此主管可以实施自定义策略来处理其子任务的
故障。
https://stackoverflow.com/questions/65536366
复制相似问题