使用RxJava调用四个api组合在一起

时间:2018-07-10 10:03:58

标签: android rx-java rx-android

我是RxJava的新手

Restapi.class

/************/
    @GET("app/dashboard")
    Observable<CategoryHomeModel[]> getCategories(@HeaderMap Map<String, String> headers);

    @GET("app/wallet/balance")
    Observable<WalletBalance> getWalletBalance(@HeaderMap Map<String, String> headers);

    @GET("/app/swap/myrateswaps")
    Observable<SwapSettings> rateMySwap(@HeaderMap Map<String, String> headers);

    @GET("/app/getsettings")
    Observable<Settings> getSettings(@HeaderMap Map<String, String> headers);
    /************/

我有四个可观察物

Observable<CategoryHomeModel[]> categoriesObservable = retrofit
            .create(Restapi.class)
            .getCategories(prepareHeaders())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());

    Observable<WalletBalance> walletObservable = retrofit
            .create(Restapi.class)
            .getWalletBalance(prepareHeaders())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());

    Observable<Settings> settingsObservable = retrofit
            .create(Restapi.class)
            .getSettings(prepareHeaders())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());

    Observable<SwapSettings> ratingsObservable = retrofit
            .create(Restapi.class)
            .rateMySwap(prepareHeaders())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());

如何将所有四个可观察对象合并为一个,并在一个地方获得响应并将所有可观察对象的所有响应一起处理


我发现可以通过合并完成此操作,如果可以,如何使用合并?

2 个答案:

答案 0 :(得分:1)

使用这种方式

List<Observable<?>> observables = Lists.newArrayList(categoriesObservable, walletObservable, settingsObservable, ratingsObservable);
            Observable.merge(observables).toList().subscribe(new Action1<List<Object>>() {
                @Override
                public void call(List<Object> objects) {
                    // success
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    // error
                }
            });

或者您可以改为使用mergeDelayError

希望这会有所帮助

答案 1 :(得分:0)

您可以使用Zip运算符

Observable<String> result = 
Observable.zip(categoriesObservable, walletObservable, settingsObservable, ratingsObservable, new Function4<CategoryHomeModel, WalletBalance, Settings, SwapSettings, String>() {
    @Override
    public String apply(CategoryHomeModel category, WalletBalance wallet, Settings settings, SwapSettings swap) {
        String res = category.name + wallet.name + settings.name + swap.name;
        // You can customize the final result based upon your requirements
        return res;
    }
});