Мне нужно сделать два запроса на услуги и объединить результаты:
ServiceA() = > [{"id":1,"name":"title"},{"id":1,"name":"title"}]
ServiceB (id
) = > {"field":"value","field1":"value"}
В настоящее время мне удалось совместить результаты, но мне нужно передать id
в качестве параметра ServiceB и получить доступ к первому результату.
То, что я пробовал до сих пор:
Retrofit repo = new Retrofit.Builder()
.baseUrl("https://api.themoviedb.org/3/genre/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Observable<GenerosResponse> Genres = repo
.create(services.class)
.getAllGeneros("movie","list","da0d692f7f62a1dc687580f79dc1e6a0")
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
Observable<ResponseMovies> Movies = repo
.create(services.class)
.getAllMovies("28","movies","da0d692f7f62a1dc687580f79dc1e6a0",12)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
Observable<CollectionsMovies> combined = Observable.zip(Genres, Movies, new Func2<GenerosResponse, ResponseMovies, CollectionsMovies>() {
@Override
public CollectionsMovies call(GenerosResponse generosResponse, ResponseMovies responseMovies) {
return new CollectionsMovies(generosResponse, responseMovies);
}
});
combined.
subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...);
Edit
Решение в соответствии с @Maxim Островидовым ответ:
private Observable<GenerosResponse> makeRequestToServiceA() {
return service.getAllGeneros("movie","list","da0d692f7f62a1dc687580f79dc1e6a0"); //some network call
}
private Observable<ResponseMovies> makeRequestToServiceB(Genre genre) {
return service.getAllMovies(genre.getId(),"movies","da0d692f7f62a1dc687580f79dc1e6a0","created_at.asc"); //some network call based on response from ServiceA
}
void doTheJob() {
makeRequestToServiceA()
.flatMap(userResponse -> Observable.just(userResponse.getGenres())) //get list from response
.flatMapIterable(baseDatas -> baseDatas)
.flatMap(new Func1<Genre, Observable<? extends ResponseMovies>>() {
@Override
public Observable<? extends ResponseMovies> call(Genre genre) {
return makeRequestToServiceB(genre);
}
}, new Func2<Genre, ResponseMovies, CollectionsMovies>() {
@Override
public CollectionsMovies call(Genre genre, ResponseMovies responseMovies) {
return new CollectionsMovies(genre,responseMovies);
}
}).
subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(....);
}