Hi all
A little confused about thread in couroutine.
Basically, we all use
<http://Dispatchers.IO|Dispatchers.IO>
for call api from network. But I am confused that where need we specified the dispatcher.
For example:
I have a UserViewModel class and FetchUserUseCase class.
Pattern 1
1. FetchUserUseCase.kt
suspend fun fetch(): UserResponse {
return runCatching {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
clientApi.get()
}
}
}
2. UserViewModel.kt
fun fetch() {
viewModelScope.launch {
fetchUserUseCase.fetch()
}
}
Pattern 2
1. FetchUserUseCase.kt
suspend fun fetch(): UserResponse {
return coroutineScope {
clientApi.get()
}
}
2. UserViewModel.kt
fun fetch() {
viewModelScope.launch {
runCatching {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
fetchUserUseCase.fetch()
}
}
}
}
Above 2 way of writing is the same ?
Where need we specified dispatcher ? ViewModel or UseCase