Rxjava Android如何使用Zip操作符

新手上路,请多包涵

我在理解我的 android 项目的 RxJava 中的 zip 运算符时遇到了很多麻烦。问题我需要能够发送网络请求来上传视频然后我需要发送网络请求来上传图片最后我需要添加描述并使用前两个请求的响应来上传视频和图片的位置 URL 以及对我的服务器的描述。

我认为 zip 运算符非常适合这项任务,因为我知道我们可以获取两个可观察对象(视频和图片请求)的响应并将它们用于我的最终任务。但我似乎无法按照我的设想让它发生。

我在找人回答如何用一些伪代码在概念上完成这件事。谢谢

原文由 feilong 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 905
2 个回答

Zip 运算符严格配对来自可观察对象的发射项。它等待两个(或更多)项目到达然后合并它们。所以是的,这将适合您的需求。

我会使用 Func2 链接前两个可观察对象的结果。请注意,如果您使用 Retrofit,此方法会更简单,因为它的 api 接口可能会返回一个可观察对象。否则,您将需要创建自己的可观察对象。

 // assuming each observable returns response in the form of String
Observable<String> movOb = Observable.create(...);
// if you use Retrofit
Observable<String> picOb = RetrofitApiManager.getService().uploadPic(...),
Observable.zip(movOb, picOb, new Func2<String, String, MyResult>() {
      @Override
      public MyResult call(String movieUploadResponse, String picUploadResponse) {
          // analyze both responses, upload them to another server
          // and return this method with a MyResult type
          return myResult;
      }
   }
)
// continue chaining this observable with subscriber
// or use it for something else

原文由 inmyth 发布,翻译遵循 CC BY-SA 4.0 许可协议

一个小例子:

 val observableOne = Observable.just("Hello", "World")
val observableTwo = Observable.just("Bye", "Friends")
val zipper = BiFunction<String, String, String> { first, second -> "$first - $second" }
Observable.zip(observableOne, observableTwo, zipper)
  .subscribe { println(it) }

这将打印:

 Hello - Bye
World - Friends


In BiFunction<String, String, String> the first String the type of the first observable, the second String is the type of the second observable, the third String 代表你的 zipper 函数返回的类型。


我在 这篇博 文中做了一个使用 zip 调用两个真实端点的小例子

原文由 Evin1_ 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题