我有一个代码,压缩两个网络请求通过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()
已弃用。
3条答案
按热度按时间clj7thdc1#
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/zip.html
kqlmhetl2#
对于大多数操作,
Flow
遵循与普通协同例程相同的规则,因此要压缩两个单独的请求,需要应用异步并发模式。在实践中,这将最终看起来像这样:
iugsix8n3#
可以使用
zip
或combine
运算符。