【问题标题】:RxJava and Retrofit - first steps with RxRxJava 和 Retrofit - Rx 的第一步
【发布时间】:2016-01-08 08:26:17
【问题描述】:

使用 RxJava(没有 Retrolambda),我想做一些 API 调用并用它完成我的数据。我不完整的对象是一个带有对象“季节”列表的“电视节目”。这个“季节”是空的,我需要用剧集来完成它。

Observable<TvShow> getDataTVShow(long idTvShow)
//get TvShow with empty seasons (except season number)

Observable<Season> getDataSeason(long idTvShow, int seasonNumber); 
//get one complete season with episodes

所以我想:

  • 获取我的“TvShow”对象(确定)
  • 从我的“TvShow”对象迭代季节(列表),并为每个季节执行一次 API 调用,以使我的季节完全完成并更新列表中的“旧”季节。
  • 然后,一旦我们拥有所需的一切,就将数据持久化到数据库中(订阅者部分)

到目前为止,我只有:

Observable<TvShow> = apiService.getDataTvShow(idTvShow)

我现在需要迭代季节,我尝试使用运算符“map”从“TvShow”对象切换到我的季节列表 (tvShow.getSeasons()),但我不确定是否是好方法.除此之外,我知道“doOnNext”将用于更新我的“旧”赛季,仅此而已。

我尝试使用这个很好的例子:Handling lists with RxJava and Retrofit in android 但我仍然卡住了:(

如果你能帮我解决这个问题,那就太好了:)

【问题讨论】:

    标签: android retrofit rx-java


    【解决方案1】:

    例如,您有两个可观察对象:

    Observable<Season> getSeason(int id)
    Observable<TvShow> getTvShow(String id)
    

    如何加载 TvShow,然后加载每个 Season 并填充 TvShow:

      Observable<TvShow> getFilledTvShow = getTvShow("123")
          .flatMap(tvShow ->
                  //make stream observable from seasons
                  Observable.from(tvShow.seasons)
                      //load each season from network
                      .flatMap(season -> getSeason(season.id))
                          //then collect all results to ArrayList
                      .collect(() -> new ArrayList<Season>(),
                          (seasons, filledSeason) -> seasons.add(filledSeason))
                          //finally fill tvShow and return it
                      .map(filledSeasons_ -> {
                         tvShow.seasons = filledSeasons_;
                         return tvShow;
                      })
          );
    

    【讨论】:

    • 非常感谢zella,它正在工作!我不知道我们可以处理我们返回的内容(返回 Observable.from ...),然后在最后返回一个 Observable。顺便说一句,我现在明白为什么要使用 lambda,这与我的样板代码有很大的不同!
    • 欢迎来到函数世界:)
    • 您可能希望使用.toList() 而不是您的collect 方法
    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多