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
Rob
07/24/2022, 2:29 AM
I think a suspend function would be more appropriate for this situation.
l
Lilly
07/24/2022, 2:52 AM
@Rob What do you mean? Collect the flow and return simple type?
j
Joffrey
07/24/2022, 8:37 AM
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.
Joffrey
07/24/2022, 8:39 AM
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
Rob
07/24/2022, 3:14 PM
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
Lilly
07/28/2022, 8:44 AM
Thanks @Rob@Joffrey. I go with a suspend function like you say