gpt4 book ai didi

android - 通过 Kotlin Coroutine Flow 压缩网络请求

转载 作者:行者123 更新时间:2023-12-04 18:18:45 26 4
gpt4 key购买 nike

我有一个通过 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 Coroutines 的 Flow 压缩请求?

我知道我可以这样做:
coroutineScope {
val date = repository.requestDate()
val time = repository.requestTime()
Result(date, time)
}

但我想通过 Flow 来实现!

我知道 channel ,但是 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

关于android - 通过 Kotlin Coroutine Flow 压缩网络请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56622619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com