使用流作为 return 调用的 API 类型

Using flow as the return type of an API call

自从过去 8 个月以来,我就开始使用 kotlin 和协程,据我所知,如果我们将它用作 api 调用的 return 类型,那不是流的最佳使用。

例如:

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

我在一次 api 调用中看到像这样的流的使用,我想知道是否应该阻止这种情况。因为流是流而不是一枪。

Flow 是一个异步数据流,它按顺序发出值并正常或异常完成。一次 api 调用不是数据流,因此使用 Flow 是一种开销。对于单个 api 调用,我会使用 suspend 函数,上下文切换到后台线程:

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

使用 Flow 取决于特定的用例。无论如何,如果你需要一个 Flow 你总是可以用一个挂起函数来创建它:

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

因此,对于单个 api 调用,最好使用 suspend 函数。另一方面,Flow 是一种可以按顺序发出多个值的类型,但它不会阻止 Flow 只发出一个值,因此它再次取决于用例。