I understand that a coroutine does not block a thread and can delegate the thread to another coroutine while it is doing its work.
I'm wondering why I shouldn't do network work in a coroutine with Dispatcher.Main.
While doing network work, you will be able to perform other UI-related tasks without blocking the Main Thread.
What I was thinking is, even if you can give up the work to another coroutine, network work can take a long time, and as a result, is it because the main thread has a lot of UI-related work to do, which wastes resources?
// works well
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
val service = RetrofitClient.buildService(GithubApiService::class.java)
val response = service.getIssues("JakeWharton", "hugo")
Log.d("TAG", " - response: $response")
}
}
@GET("/repos/{user}/{repo}/issues")
suspend fun getIssues(
@Path("user") user: String,
@Path("repo") repo: String
): List<Issue>
There is nothing wrong with using
Dispatchers.Mainto call yourgetIssuessuspend function. It doesn't matter what dispatcher you are using to callsuspendfunctions, becausesuspendfunctions do not block (unless you incorrectly defined the suspend function yourself by putting blocking code in it). You only have to avoid calling blocking functions on the main thread.If you defined a blocking network function, it would freeze your app if you called it on the main thread.