改造和RxJava:如何组合两个请求并访问这两个结果?
我需要对服务提出两个请求并合并结果:
服务 A() = >[{"id":1,"name":"title"},{"id":1,"name":"title"}]
服务B(id
) => {"field":"value","field1":"value"}
目前,我已经设法合并了结果,但我需要作为参数传递给ServiceB并访问第一个结果。id
到目前为止,我尝试了什么:
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(...);
编辑
根据@Maxim Ostrovidov的答案的解决方案:
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(....);
}