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

Colton Idle

03/29/2024, 4:53 AM
I'm in an android viewModel (so I have access to viewModelScope).
Copy code
fun checkSomethingAndUpdateState(){
  viewModelScope.launch {
    val abc = repo.getSomething()
    updateState(abc)
  }
}
Repo.getSomething() is simple because it uses a 3rd part library that's already "main safe"
Copy code
suspend fun getSomething(){
 val foo = thirdParty.getThing() <=== according to 3rd party docs, this happens on IO dispatcher, so its main safe
}
My question is whether or not my viewModelScope.launch() {} should pass in a dispatchers? I guess not right since all of the code it calls is main safe, and my only consideration is really "updating" the ui state, which is fine to happen on main thread (i.e. updateState)
m

mohamed rejeb

03/29/2024, 6:44 AM
I think that you should pass the dispatcher as soon as possible when needed. So let's say that your
getSomething
method is not main safe, use
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
before even reaching the view model, because this method can be called from multiple places in your code and you don't want to use
<http://Dispatchers.IO|Dispatchers.IO>
each time you call it. Also, in the future, if for some reason you need to change the
Dispatcher
, you will need to change it in all call places for that method, which is hard to maintain. Also for updating the state, especially if it is Compose
State
not
Flow
, make sure that you are updating it on
Dispatchers.Main
, otherwise you may encounter some crashes.
👎 1
🤔 1
s

Sam

03/29/2024, 2:21 PM
@Colton Idle your intuition is right. No need for a dispatcher. From the docs:
It's normal for
suspend
functions to operate on the main thread. It's also common to launch coroutines on the main thread.
👍 1
2 Views