Is there any difference in : ```suspend fun getFlo...
# coroutines
j
Is there any difference in :
Copy code
suspend fun getFlow() = withContext(<http://Dispachers.IO|Dispachers.IO>) {
     flow { ... }
}
and
Copy code
fun getFlow() = flow { ... }.flowOn(<http://Dispachers.IO|Dispachers.IO>)
j
Yes, the first one doesn't make sense, and doesn't do what you think it does
In the first example,
withContext
will only affect the creation of the flow (which is very quick because it doesn't execute the body of the
flow
builder). It will suspend the caller and potentially do a context switch just for an instant, just the time it takes to instantiate a flow and return it. Only the flow instantiation and the return will be executed in the IO dispatcher.
In the second example, the caller is not suspended at all, a flow is constructed immediately, and the body of the flow itself will be executed on the IO dispatcher when the flow is collected. The creation of the flow and the return are executed in the caller's thread
j
ohh got it so I guess the equivalent function of flowOn will be
Copy code
suspend fun getFlow() =  flow {
    withContext(Dispatchers.IO) {  }
}
👎 1
m
flowOn
affects not only
flow {}
block but also any
map
,
transform
and similar functions in chain before
flowOn
call. In your example behavior will be the same, but if you add
map
between
flow {}
and
flowOn
behavior will become different
👍 2
p
Generally, do not use
withContext
inside the
flow { }
flow builder. If you try to call
emit
inside the
withContext
block, it will throw an exception. You should use flowOn if you want to change the dispatcher on which the flow executes the code
m
i don’t think withContext will do anything really, i might be wrong. There is no suspension point in the function
p
I had assumed that code was omitted for brevity
2