你可以在下面看到两个方法,第一个使用了withContext和coroutineScope,第二个函数只使用了协程Scope。如果它只使用了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) }
}
}
在这种情况下,withContext
中不需要coroutineScope
,因为withContext
已经为您完成了此操作。
在某些情况下,在with Context
中使用coroutineScope
可能会很有用。
withContext(ioDispatcher) {
coroutineScope {
launch { tasksRemoteDataSource.deleteAllTasks() }
launch { tasksLocalDataSource.deleteAllTasks() }
}
coroutineScope {
launch { tasksRemoteDataSource.deleteAllTasks() }
launch { tasksLocalDataSource.deleteAllTasks() }
}
}
这里coroutineScope
用于并行分解和描述并发任务集。