In general is it safe to assume the following are ...
# coroutines
y
In general is it safe to assume the following are roughly similar in cost?
Copy code
suspend fun getX() : X
fun getXFlow(): Flow<X>

val a = getX()
val b = getXFlow().first()
Obviously the implementations may be different (one off query vs query and subscribe). But can the implementation optimise the call to first() which is the when the subscription happens and short circuit it? Othewise it's tempting to put both variants on most repository methods. But it would be nice if there was an expectation that first() should optimise to the suspend fun case.
a
No, it's not safe to assume that. In the case of something like a database query it's the difference between performing a one and done query vs. performing that same query and setting up/tearing down table change observers, the cost of which could vary dramatically depending on your data source
👍🏻 1
👍 1
Instead of taking an all or nothing stance from the repository in isolation, offer the operations your layers above actually use. Many calls will only need one or the other.
y
Yep, that's what I figured. I'll end up exposing suspend and flow variants of both in a lot of cases.
I'd like to have enough understanding of the typical implementation flow to consider if it should be the case that flow.first() can be optimised to have the same cost/effect as the suspend form. But I think in reality, most implementations will be coded as you suggest.
Ok, never fixable since it's an extension method never seen by implementations.
Copy code
public suspend fun <T> Flow<T>.first(): T {