android 通过Kotlin协同程序流压缩网络请求

ioekq8ef  于 2023-03-06  发布在  Android
关注(0)|答案(3)|浏览(204)

我有一个代码,压缩两个网络请求通过RxJava:

Single.zip(repository.requestDate(), repository.requestTime()) {
  date, time -> Result(date, time)
}

这意味着repository.requestDate()/repository.requestTime()返回Single<T>
如果我想使用协程,我需要将请求更改为:

@GET('link/date')
suspend fun requestDate() : Date

@GET('link/time')
suspend fun requestTime() : Time

但是,我如何通过Kotlin协同程序中的Flow压缩请求?
我知道我可以这样做:

coroutineScope {
   val date = repository.requestDate()
   val time = repository.requestTime()
   Result(date, time)
}

但我想通过Flow来完成!

我知道通道,但Channels.zip()已弃用。

clj7thdc

clj7thdc1#

val dateFlow = flowOf(repository.requestDate())
val timeFlow = flowOf(repository.requestTime())
val zippedFlow = dateFlow.zip(timeFlow) { date, time -> Result(date, time) }

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/zip.html

kqlmhetl

kqlmhetl2#

对于大多数操作,Flow遵循与普通协同例程相同的规则,因此要压缩两个单独的请求,需要应用异步并发模式。
在实践中,这将最终看起来像这样:

flow {
    emit(coroutineScope/withContext(SomeDispatcher) {
        val date = async { repository.requestDate() }
        val time = async { repository.requestTime() }
        Result(date.await(), time.await())
    })
}
iugsix8n

iugsix8n3#

可以使用zipcombine运算符。

相关问题