问题描述
当我并行执行大约 20-25 个异步任务时,我遇到了一个有趣的问题。
这是我截取的代码:
private val ioScope = CoroutineScope(Dispatchers.IO)
private suspend fun getSquadPlayerDetails(
repository: PlayersRepository,squadData: SquadInclude
): List<TeamSquadMemberModel> {
val playerTasks = mutableListOf<Deferred<GetPlayerByIdResponse?>>()
val playerTasksResult = mutableListOf<GetPlayerByIdResponse?>()
val playerDetailsJob = ioScope.launch {
squadData.data.forEach { squadPlayer ->
val playerDetailsTask = async {
repository.getPlayerInfo(squadPlayer.player_id).response
}
playerTasks.add(playerDetailsTask)
}
val result = playerTasks.awaitAll()
playerTasksResult.addAll(result)
}
playerDetailsJob.join()
}
2021-02-08 09:03:33.878 13338-15116/E/AndroidRuntime:致命异常:DefaultDispatcher-worker-3 进程:,PID:13338 java.lang.NullPointerException:尝试在空对象引用上调用接口方法“boolean kotlinx.coroutines.Deferred.start()” 在 kotlinx.coroutines.AwaitAll.await(Await.kt:66) 在 kotlinx.coroutines.AwaitKt.awaitAll(Await.kt:38) 在 $1.invokeSuspend(GetTeamDetailsUseCase.kt:70) 在 kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 在 kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56) 在 kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571) 在 kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738) 在 kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678) 在 kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
看起来有时由于某种原因正在执行的协程抛出异常但为什么我无法弄清楚。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)