https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Jason

11/22/2019, 9:21 AM
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

elizarov

11/22/2019, 9:36 AM
j

Jason

11/22/2019, 9:48 AM
Thank you. Let me considering
d

dekans

11/22/2019, 10:34 AM
withContext
already creates its
CoroutineScope
AFAIU, no need for an additionnal one.
s

streetsofboston

11/22/2019, 1:01 PM
j

Jason

11/22/2019, 11:59 PM
By the way, how to test UseCase in option 1 ? We can not change dispatchers ???
s

streetsofboston

11/23/2019, 3:01 AM
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

Jason

11/23/2019, 3:27 AM
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

streetsofboston

11/23/2019, 4:05 AM
Yeah... That's a know issue... If you Google this error you'll find it.
z

zak.taccardi

12/02/2019, 4:04 PM
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
2 Views