Retrofit and RxJava: How to combine two requests and get access to both results?

后端 未结 2 1034
挽巷
挽巷 2020-11-28 10:28

I need to make two requests for services and combine it results:

ServiceA() => [{\"id\":1,\"name\":\"title\"},{\"id\":1,\"name\":\"title\"}]

S

相关标签:
2条回答
  • 2020-11-28 11:02

    The operator you are looking for is flatMap()

    serviceA.getAllGeneros("movie","list","da0d692f7f62a1dc687580f79dc1e6a0")
        .flatMap(genres -> serviceB.getAllMovies(genres.getId() ......))
    
    0 讨论(0)
  • 2020-11-28 11:03

    As I understand - you need to make a request based on result of another request and combine both results. For that purpose you can use this flatMap operator variant: Observable.flatMap(Func1 collectionSelector, Func2 resultSelector)

    Returns an Observable that emits the results of a specified function to the pair of values emitted by the source Observable and a specified collection Observable.

    Simple example to point you how to rewrite your code:

    private Observable<String> makeRequestToServiceA() {
        return Observable.just("serviceA response"); //some network call
    }
    
    private Observable<String> makeRequestToServiceB(String serviceAResponse) {
        return Observable.just("serviceB response"); //some network call based on response from ServiceA
    }
    
    private void doTheJob() {
        makeRequestToServiceA()
                .flatMap(new Func1<String, Observable<? extends String>>() {
                    @Override
                    public Observable<? extends String> call(String responseFromServiceA) {
                        //make second request based on response from ServiceA
                        return makeRequestToServiceB(responseFromServiceA);
                    }
                }, new Func2<String, String, Observable<String>>() {
                    @Override
                    public Observable<String> call(String responseFromServiceA, String responseFromServiceB) {
                        //combine results
                        return Observable.just("here is combined result!");
                    }
                })
                //apply schedulers, subscribe etc
    }
    

    Using lambdas:

    private void doTheJob() {
        makeRequestToServiceA()
                .flatMap(responseFromServiceA -> makeRequestToServiceB(responseFromServiceA),
                        (responseFromServiceA, responseFromServiceB) -> Observable.just("here is combined result!"))
                //...
    }
    
    0 讨论(0)
提交回复
热议问题