Issue
I have the following interface to fetch recipes
interface FoodService {
@GET(EndPoint.COMPLEX_SEARCH)
suspend fun fetchComplexSearch(@Query("apiKey") apiKey: String): ResultModel
}
This works find using a flow builder
override fun complexSearch(apiKey: String): Flow<List<ComplexSearchEntity>> {
return flow {
val resultModel = foodService.fetchComplexSearch(apiKey)
val listOfComplexSearchEntity = resultModel.results.map { complexSearchModel ->
mapperDataToDomain.map(complexSearchModel)
}
emit(listOfComplexSearchEntity)
}
}
However, I get an error when I use the extension asFlow
override fun complexSearch(apiKey: String): Flow<List<ComplexSearchEntity>> {
return foodService.fetchComplexSearch(apiKey).results.map {
mapperDataToDomain.map(it)
}.asFlow()
}
Error 1
Required:
Flow<List<ComplexSearchEntity>>
Found:
Flow<ComplexSearchEntity>
Error 2
Suspend function 'fetchComplexSearch' should be called only from a coroutine or another suspend function
Solution
It doesn't do the same thing at all, hence the error.
In the first case, complexSearch
immediately returns a cold flow without doing any work. No code from the lambda is executed, so no need to suspend anything. The collector of this cold flow will provide a coroutine environment for the collection and the suspension. Each time the collector asks for a new element, the content of your flow { ... }
lambda will proceed until the next emit()
.
In the second case, you're performing all the work immediately to build a list, and only then convert that list into a flow before returning it. So all your asynchronism happens immediately and needs to be executing in a coroutine. The flow is just a wrapper around the list in this case.
Also, I'm not sure the code is doing what you want, because you're returning a flow of a single element (at least in the first case). This is usually better served by a suspend function rather than a Flow
, which also better informs the users that this is a one-shot call. An API returning a Flow
of a single element is misleading because the users of this API would likely expect to susbcribe to this flow and get updates.
Answered By - Joffrey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.