Function returns flow object. Is meaningless to ma...
# coroutines
t
Function returns flow object. Is meaningless to make that function suspendable?
j
Generally, yes. But it also might depend on the use case. A lot of flows are cold, which means they are only really started when a collector starts to
collect
it. Nothing really happens when creating a
Flow
(so calling a function that returns a
Flow
often does nothing in itself). In this case, there is no real reason to make a function suspend (actually a good rule of thumb is to avoid marking a function
suspend
if the compiler doesn't force you). Sometimes, some functions can do some suspending stuff that starts something hot before returning a flow. But this is less common. This can be the case for instance if a function needs to start a subscription to something right away, and provide a guarantee to the caller that when the function returns, the subscription has happened, so they can do stuff after the subscription, but before collecting the flow.
👍 5
K 2
a
SharedFlow.onSubscription takes care of a class of use cases for coordinating hot flow subscription guarantees https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/on-subscription.html
👍 2
m
If you use Detekt in your Kotlin codebase, I added the following opt-in rule that addresses this: https://detekt.github.io/detekt/coroutines.html#suspendfunwithflowreturntype
For more context, here is the original issue that led to the rule being introduced: https://github.com/detekt/detekt/issues/3086