通过Kotlin Coroutine Flow进行Zip网络请求 [英] Zip network requests via Kotlin Coroutine Flow

查看:264
本文介绍了通过Kotlin Coroutine Flow进行Zip网络请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a code which zips two network requests via RxJava:

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

这意味着 repository.requestDate()/ repository.requestTime()返回 Single< T>

如果我想使用协程,则需要将请求更改为:

If I want to use Coroutines I need to change requests to:

@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来做!

我了解Channels,但已弃用 Channels.zip().

I know about Channels, but Channels.zip() is deprecated.

推荐答案

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

这篇关于通过Kotlin Coroutine Flow进行Zip网络请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆