Colton Idle
03/29/2024, 4:53 AMfun 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"
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)mohamed rejeb
03/29/2024, 6:44 AMgetSomething
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.Sam
03/29/2024, 2:21 PMIt's normal forfunctions to operate on the main thread. It's also common to launch coroutines on the main thread.suspend