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

后端 未结 2 1049
挽巷
挽巷 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: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 makeRequestToServiceA() {
        return Observable.just("serviceA response"); //some network call
    }
    
    private Observable makeRequestToServiceB(String serviceAResponse) {
        return Observable.just("serviceB response"); //some network call based on response from ServiceA
    }
    
    private void doTheJob() {
        makeRequestToServiceA()
                .flatMap(new Func1>() {
                    @Override
                    public Observable call(String responseFromServiceA) {
                        //make second request based on response from ServiceA
                        return makeRequestToServiceB(responseFromServiceA);
                    }
                }, new Func2>() {
                    @Override
                    public Observable 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!"))
                //...
    }
    

提交回复
热议问题