RxJava and Retrofit - first steps with Rx

核能气质少年 提交于 2019-12-21 17:32:08

问题


With RxJava (without Retrolambda), I would like to do some API calls and complete my data with it. My incomplete object is a 'TvShow' with a list of object 'Season'. This 'Season' is empty and I need to complete it with episodes.

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

So I want to:

  • Get my 'TvShow' object (OK)
  • Iterate over seasons (List <\Season>) from my 'TvShow' object and do for each season an API call to get my season fully completed and update my 'old' season in the list.
  • Then once we have all we need, persist data into the database (subscriber part)

Until now, I only have :

Observable<TvShow> = apiService.getDataTvShow(idTvShow)

I need now to iterate over seasons, I tried to use operator 'map' to switch from 'TvShow' object to my list of seasons (tvShow.getSeasons()) but I'm not sure to be in the good way. Beside that, I know 'doOnNext' will be used to update my 'old' season, that's it.

I tried to work with this good example: Handling lists with RxJava and Retrofit in android but I'm still stuck :(

If you can help me solve this problem, it would be great :)


回答1:


For example you have two observables:

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

How load TvShow then load each Season and fill 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;
                  })
      );


来源:https://stackoverflow.com/questions/32759291/rxjava-and-retrofit-first-steps-with-rx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!