0

I'm learning RxJava. I'm retrieving film information from two API.

  • The first API (Api1 class) receives an id and returns a JSON (Api1Dto class):

{ id : "123456", title : "Top Secret", api2Id : "7787" }

  • The second API (Api2 class) receives an api2id and returns a JSON (Api2Dto class):

{api2Id : "58582", "director" : "Peter Jackson" }

I want, from an id, compose a structure with all those fields (Film class):

{ id: "123456", title : "Muahaha", api2Id : "5552", director : "Uncle Joe" }

I have this code:

 public Observable<Film> getById(final String id) { return api1.getById(id).map(new Func1<Api1Dto, Film>() { @Override public Film call(Api1Dto dto1) { Film film = new Film(); film.id = dto1.id; film.title = dto1.title; film.api2Id = dto1.api2Id; return film; } }).flatMap(new Func1<Film, Observable<Film>>() { @Override public Observable<Film> call(final Film film) { return api2.getById(film.api2Id).map(new Func1<Api2Dto, Film>() { @Override public Film call(Api2Dto dto2) { film.director = dto2.director; return film; } }); } }); } 

It works, but I wonder if this is the correct way to do it or exists a better/more elegant solution using functions that RxJava provides.

1 Answer 1

1

A little better "elegant" way : flatMap can do the map job for you.

 public Observable<Film> getById(final String id) { return api1.getById(id).map(dto1 -> { Film film = new Film(); film.id = dto1.id; film.title = dto1.title; film.api2Id = dto1.api2Id; return film; }).flatMap(film -> api2.getById(film.api2Id), (film, dto2) -> { film.director = dto2.director; return film; }); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.