【问题标题】:What is the difference between coroutineScope { launch { code } } and withContext(iODispatcher) { code } in the Architecture Sample by Google?Google Architecture Sample 中的 coroutineScope { launch { code } } 和 withContext(iODispatcher) { code } 有什么区别?
【发布时间】:2021-08-26 05:15:59
【问题描述】:

代码:https://github.com/android/architecture-samples/blob/main/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/DefaultTasksRepository.kt

来自上述代码链接的片段:

    override suspend fun activateTask(taskId: String) {
        withContext(ioDispatcher) {
            (getTaskWithId(taskId) as? Success)?.let { it ->
                activateTask(it.data)
            }
        }
    }

    override suspend fun clearCompletedTasks() {
        coroutineScope {
            launch { tasksRemoteDataSource.clearCompletedTasks() }
            launch { tasksLocalDataSource.clearCompletedTasks() }
        }
    }

    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) }
        }
    }

什么时候用哪个?

有时coroutineScope { launch { code } }withContext(iODispatcher) 内!

何时使用:coroutineScope { launch { code } }

何时使用:withContext(iODispatcher)

何时使用它们嵌套:coroutineScope { launch { code } }withContext(iODispatcher)

【问题讨论】:

    标签: android kotlin kotlin-coroutines coroutinescope


    【解决方案1】:

    withContext(ioDispatcher) 应该用于将在{} 中运行的阻塞 IO 任务卸载到共享线程池。

    coroutineScope { } 创建一个子作用域,它从父作用域的协程上下文继承 coroutineContext。它应该用于“工作的并行分解”。这也意味着当作用域中的任何子协程失败时,任何其他子作用域也将被取消

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 2014-05-10
      • 2020-02-05
      • 2017-06-17
      相关资源
      最近更新 更多