Hi all, If we use StateFlow in VMs , is it okay to move viewmodelScope directly to IO Dispatcher , a...
p
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
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
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
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
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
Also, hard-coding Dispatchers should be avoided since it will make your Unit Testing really hard if not impossible.