Home > Mobile >  Using flow as the return type of an API call
Using flow as the return type of an API call

Time:03-24

I am into kotlin and co-routines since last 8 months, as per my understanding it is not optimal usage of flow if we use it as the return type of an api call.

e.g:

fun getCoutries(): Flow<List<Country>> = flow {
   emit(apiInterface.getAllCountries())
}

I am seeing usage of flow like these in one shot api calls, I want to know if this should be discouraged or not. Since flow is to be a stream rather than being one shot.

CodePudding user response:

Flow is an asynchronous data stream that sequentially emits values and completes normally or with an exception. One shot api call is not a data stream so using Flow for that is an overhead. For a single api call I would use a suspend function with context switching to background thread:

fun suspend getCountries(): List<Country> = withContext(Dispatchers.IO) {
    apiInterface.getAllCountries()
}

Using a Flow depends on a particular use case. Anyway if you need a Flow you can always create it out of a suspend function:

fun getCountriesFlow(): Flow<List<Country>> = flow {
    // make request and emit items each ten seconds
    while(true) {
        emit(getCountries())
        delay(10000)
    }
}

So for a single api call it is better to use a suspend function. From the other hand Flow is a type that can emit multiple values sequentially, but it doesn't prevent the Flow from emitting only one value, so again it depends on the use case.

  • Related