1

you can see below two methods, the first one using withContext and coroutineScope and second function using only coroutine Scope. What if it will used only withContext? or only coroutine scope? Why both need to be used?

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) }
    }
}
Kumar Kalluri
  • 493
  • 2
  • 6
  • 26
  • Does this answer your question? [kotlin coroutines, what is the difference between coroutineScope and withContext](https://stackoverflow.com/questions/56858624/kotlin-coroutines-what-is-the-difference-between-coroutinescope-and-withcontext) – EraftYps Jul 01 '20 at 23:46
  • but they explained as separated functions , here the cases are what if using both – Kumar Kalluri Jul 01 '20 at 23:53

1 Answers1

0

In that case there is no need for coroutineScope inside withContext, since withContext does this for you already.

There are situations where using coroutineScope inside withContext could be useful.

withContext(ioDispatcher) {
    coroutineScope {
        launch { tasksRemoteDataSource.deleteAllTasks() }
        launch { tasksLocalDataSource.deleteAllTasks() }
    }
    coroutineScope {
        launch { tasksRemoteDataSource.deleteAllTasks() }
        launch { tasksLocalDataSource.deleteAllTasks() }
    }
}

Here the coroutineScopes are use for parallel decomposition and to delineate the set of concurrent tasks.

Dominic Fischer
  • 1,695
  • 10
  • 14