您可以看到下面两个方法,第一个使用withContext和coroutineScope,第二个函数仅使用协程作用域。如果它只使用withContext呢?还是只有协程作用域?为什么两者都需要使用?
override suspend fun deleteAllTasks() {
withContext(ioDispatcher) {
coroutineScope {
launch { tasksRemoteDataSource.deleteAllTasks() }
launch { tasksLocalDataSource.deleteAllTasks() }
}
}
}
override suspend fun deleteTask(taskId: String) {
coroutineScope {
launch { tasksRemoteDataSource.deleteTask(taskId) }
launch { tasksLocalDataSource.deleteTask(taskId) }
}
}发布于 2020-07-02 09:00:37
在这种情况下,不需要在withContext中使用coroutineScope,因为withContext已经为您完成了这项工作。
在某些情况下,在withContext中使用coroutineScope可能会很有用。
withContext(ioDispatcher) {
coroutineScope {
launch { tasksRemoteDataSource.deleteAllTasks() }
launch { tasksLocalDataSource.deleteAllTasks() }
}
coroutineScope {
launch { tasksRemoteDataSource.deleteAllTasks() }
launch { tasksLocalDataSource.deleteAllTasks() }
}
}这里,coroutineScope用于并行分解和描述并发任务集。
https://stackoverflow.com/questions/62686809
复制相似问题