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
It is but you should inject your Dispatchers in order to test your viewModel easily
g
Gioele Dev
12/04/2022, 3:59 PM
i dont' understand , is correct use a different Dispatchers or no?
u
uli
12/04/2022, 4:06 PM
Yes and no 😉
uli
12/04/2022, 4:07 PM
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.
uli
12/04/2022, 4:08 PM
Not true in the sense that this dispatching to a background thread is the responsibility of the method doing the actual blocking.
uli
12/04/2022, 4:11 PM
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:
So no one downstream needs to guess, what the method is doing and which dispatcher is the right one to call it on.
uli
12/04/2022, 4:12 PM
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.”
uli
12/04/2022, 4:13 PM
The same should always hold true for coroutines based libraries like retrofit, room, …