muliyul
03/11/2021, 5:07 PMrunBlocking {
...
collection.asFlow().flowOn(<http://Dispatchers.IO|Dispatchers.IO>).fold(0) { acc, next ->
acc + calculate(next)
}
}
Does it matter if the calculate
function is suspending or not in terms of performance?Alex Vasilkov
03/12/2021, 5:35 AMflowOn
operator only applies to preceding operators, you probably want it after fold
.
• <http://Dispatchers.IO|Dispatchers.IO>
is meant for io operations that can spent a lot of time just waiting. For cpu intensive tasks Dispatchers.Default
should be preferred. It is not clear what calculate
function does though.
If calculate
function does some local cpu computation I can't see why it should suspend. If it involves io operations (e.g. API call, disk read, etc) then it can be either suspending or blocking. Using blocking operation will avoid dispatching but you will hardly notice the difference as IO will take significantly more time, imo. So I'd use suspending function just to avoid having any blocking functions in the code.
Also, you probably don't need to use Flow
at all here:
val result = withContext(Dispatchers.Default) { collection.fold(0) {...} }