Jason
11/22/2019, 9:21 AM<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 UseCaseJason
11/22/2019, 9:24 AMelizarov
11/22/2019, 9:36 AMJason
11/22/2019, 9:48 AMdekans
11/22/2019, 10:34 AMwithContext
already creates its CoroutineScope
AFAIU, no need for an additionnal one.streetsofboston
11/22/2019, 1:01 PMJason
11/22/2019, 11:59 PMstreetsofboston
11/23/2019, 3:01 AMscope = viewModelScope + context
where context is provided as an constructor input parameter. You could provide a TestCoroutineDispatcher as input for context
.Jason
11/23/2019, 3:27 AMval testScope = TestCoroutineScope(testDispatcher)
beforeEachTest {
Dispatchers.setMain(testDispatcher)
}
afterEachTest {
Dispatchers.resetMain()
testScope.cleanupTestCoroutines()
}
return testScope
Jason
11/23/2019, 3:27 AMThis job has not completed yet
java.lang.IllegalStateException: This job has not completed yet
streetsofboston
11/23/2019, 4:05 AMzak.taccardi
12/02/2019, 4:04 PMUseCase
pattern doesn’t really make sense in Kotlin. It’s just a higher order function https://twitter.com/ZakTaccardi/status/1199764248861261824?s=20