Hi i am new in coroutines :slightly_smiling_face: ...
# coroutines
g
Hi i am new in coroutines 🙂 i have a simply question.. from viewModel i get data from server with retrofit, viewModel -> useCase -> Repository... retrofit. When create coroutine i use the classic viewModelScope.launch { ... in some book i read that for network i have to use or better to use
Copy code
viewModelScope.launch( <http://Dispatchers.IO|Dispatchers.IO>)
is it correct ?
m
It is but you should inject your Dispatchers in order to test your viewModel easily
g
i dont' understand , is correct use a different Dispatchers or no?
u
Yes and no 😉
True in the sense that to do blocking IO, you should dispatch via Dispatchers.IO so that you only block one of many io threads.
Not true in the sense that this dispatching to a background thread is the responsibility of the method doing the actual blocking.
The contract in coroutines is, that a suspend method does not block. i.e. this is not guaranteed but is expected from the author of suspend methods. So if someone needs to block, let’s say for a blocking read from the network they would write:
Copy code
suspend fun Socket.readMyData(int count) : ByteArray = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
  return read(count)
}
So no one downstream needs to guess, what the method is doing and which dispatcher is the right one to call it on.
So, to answer your question: “No need to call retrofit on the IO dispatcher. If you use the suspend methods of retrofit, it’s retrofit’s responsibility to not block your main thread.”
The same should always hold true for coroutines based libraries like retrofit, room, …