繁体   English   中英

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

[英]Zip network requests via Kotlin Coroutine Flow

我有一个通过 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,但Channels.zip()已被弃用。

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

对于大多数操作Flow遵循与普通协程相同的规则,因此要压缩两个单独的请求,您需要应用异步并发模式

在实践中,这将最终看起来像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM