Hi all, If we use StateFlow in VMs , is it okay to move viewmodelScope directly to IO Dispatcher , and use it for every launch instead of the given one which runs on main?
Something like:-
Copy code
fun CoroutineScope.ioLaunch(
launchBody: suspend CoroutineScope.() -> Unit
): Job {
return this.launch(context = <http://Dispatchers.IO|Dispatchers.IO>, block = launchBody)
}
viewmodelScope.ioLaunch{
//Do things
}
Because when using StateFlow , we can update it from any thread and UI will not break
x
xoangon
10/18/2023, 6:13 AM
VMs shouldn't need to do any context switch if you're using a CLEAN architecture. The actual `suspend fun`ctions doing blocking or cpu-intensive operations should be the ones in charge of internally switching the context, thus providing main-safe `suspend fun`ctions.
This is explained in the Best Practices for Coroutines in Android tutorial
👆🏼 1
👆 2
p
Prateek Kumar
10/18/2023, 6:17 AM
I totally get this part , but if we think about if , if we start the scope in io Dispathcer , there will not be any dispatcher switching as the only reason we do something inside a launch is , that suspend is for sure going to do some io operation, then why not just keep it always at io
x
xoangon
10/18/2023, 6:34 AM
Not at all, suspending goes far beyond that just io operations. Take the
sequence
builder function as an example. That function has a
suspend
function type as an argument that allows for declaring algorithms to create infinite collections in a yield-based style
xoangon
10/18/2023, 6:35 AM
And that's just one example. You may want to perform CPU-intensive or time-intensive operations using the
Dispatchers.default
and that's also not IO
c
ceedee
10/18/2023, 7:39 AM
Also, hard-coding Dispatchers should be avoided since it will make your Unit Testing really hard if not impossible.