Assume I have this: ```runBlocking { ... collect...
# coroutines
m
Assume I have this:
Copy code
runBlocking {
 ...
 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?
a
I see few issues with the code itself: •
flowOn
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) {...} }