【问题标题】:Nested Network calls using Rx-Android and Retrofit使用 Rx-Android 和 Retrofit 的嵌套网络调用
【发布时间】:2023-03-11 23:20:01
【问题描述】:

我正在开发一个应用程序,我曾使用 Rx-android 和 Retrofit 来执行网络请求,但现在项目中有一个要求,我必须执行嵌套网络调用。我尝试用谷歌搜索它但没有找到任何好的文章。如果有人研究过这个主题,请告诉我你的发现。

【问题讨论】:

    标签: android rx-java retrofit2 rx-android


    【解决方案1】:

    假设您正在使用带有 rxjava 适配器的改造:

    fun firstRequest(): Single<Response<String>>
    
    fun secondRequest(idFromFirstRequest: String): Single<Response<ResponseBody>>
    

    使用flatmap 运算符链接网络调用:

    firstRequest()
      // do more operators on the request, like transforming the object, or showing it first on the ui
      .flatMap { stringId -> secondRequest(stringId) }
      // you can flatMap here again to chain another network requests
      // .flatMap { thirdRequest() }
      // .flatMap { fourthRequest() }
      // and so on...
    

    【讨论】:

      【解决方案2】:

      API 链相关的文章很多,最简单的实现方法是使用 Rx-Java 方法

      1) 使用 RxJava Zip 运算符(用于并行请求)

      2) 使用 RxJava flatMap() 操作符(依次请求)

      更多详细示例请参考这两个链接

      Synchronizing Network Calls With RxJava

      Multiple api request using retrofit and rx java

      【讨论】:

        猜你喜欢
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        • 2015-04-27
        • 1970-01-01
        • 2017-10-03
        • 2015-04-07
        • 2018-08-23
        • 2016-11-09
        相关资源
        最近更新 更多