I would like to return a `flow of T` if cache is e...
# coroutines
l
I would like to return a
flow of T
if cache is empty, otherwise T (as flow). I'm wondering which way is more appropriate:
Copy code
fun fetchStuff(): Flow<Stuff> = 
        if (cache.isNotEmpty()) {
            cache.asFlow()
        } else {
            api.fetchStuff()
        }.map { model -> model.toStuffModel() }

or

fun fetchStuff(): Flow<Stuff> = flow {
        if (cache.isNotEmpty()) {
            emit(cache.first())
        } else {
            emitAll(api.fetchStuff())
        }
    }.map { model -> model.toStuffModel() }
r
I think a suspend function would be more appropriate for this situation.
l
@Rob What do you mean? Collect the flow and return simple type?
j
What does
api.fetchStuff()
return? Suspend functions are more appropriate and easier to work with than flows of 1 element. It depends on whether your flows here have only one element, though. It is unclear from the code.
If those flows actually have multiple elements, I would go with something like the first option, but with the
if
expression extracted into a separate function
r
Since this Flow returns a single result, it probably is better done with a suspend function like this. If you wanted to return multiple values, a cached result and then update it with data from the API, then a flow makes sense.
Copy code
suspend fun fetchStuff(): Stuff {
    val model = if (cache.isNotEmpty()) cache else api.fetchStuff()
    return model.toStuffModel()
}
l
Thanks @Rob @Joffrey. I go with a suspend function like you say