Hi all A little confused about thread in couroutin...
# coroutines
j
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
Copy code
suspend  fun fetch(): UserResponse {
   return runCatching {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                clientApi.get()
            }
        }
}
2. UserViewModel.kt
Copy code
fun fetch() {
   viewModelScope.launch {
     fetchUserUseCase.fetch()
   }
}
Pattern 2
1. FetchUserUseCase.kt
Copy code
suspend  fun fetch(): UserResponse {
   return coroutineScope {
          clientApi.get()
   }
}
2. UserViewModel.kt
Copy code
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
@elizarov Do you have any idea for this case?
e
đź‘Ť 1
j
Thank you. Let me considering
d
withContext
already creates its
CoroutineScope
AFAIU, no need for an additionnal one.
s
j
By the way, how to test UseCase in option 1 ? We can not change dispatchers ???
s
You could do
scope = viewModelScope + context
where context is provided as an constructor input parameter. You could provide a TestCoroutineDispatcher as input for
context
.
j
No, in UseCase the Dispatchers.IO is specified so how to change it before test ?
Copy code
val testScope = TestCoroutineScope(testDispatcher)

    beforeEachTest {
        Dispatchers.setMain(testDispatcher)
    }
    afterEachTest {
        Dispatchers.resetMain()
        testScope.cleanupTestCoroutines()
    }
    return testScope
Copy code
This job has not completed yet
java.lang.IllegalStateException: This job has not completed yet
s
Yeah... That's a know issue... If you Google this error you'll find it.
z
side note,
UseCase
pattern doesn’t really make sense in Kotlin. It’s just a higher order function https://twitter.com/ZakTaccardi/status/1199764248861261824?s=20