如何使用RxJava2的Zip运算符?

时间:2019-02-05 04:55:06

标签: android rx-java2 zip-operator

我有2个来自Retrofit的电话,它们从2个不同的Subreddit中提取图像。我需要有关如何使用observables#zip()运算符的帮助,以将两个结果都放在一个列表中。如果有人可以帮助我,我将不胜感激。

以下是翻新配置:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.reddit.com/r/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

RedditAPI backendApi = retrofit.create(RedditAPI.class);

我正在创建一个观测值列表以存储多个调用的结果:

List<Observable<?>> requests = new ArrayList<>();

requests.add((Observable<?>) backendApi.getpics());
requests.add((Observable<?>) backendApi.getearthporn());

我不知道Zip运算符的正确用法。这是我所拥有的:

Observable.zip(
        requests, 
        new Function<Object[], Object>() {
            @Override
            public Object apply(Object[] objects) throws Exception {                                            
                return new Object();
            }
        }).subscribe(new Consumer<Object>() {
                         @Override
                         public void accept(Object o) throws Exception {       
                            Log.d(TAG, "accept: "+o.toString());
                         }
                     }, new Consumer<Throwable>() {
                         @Override
                         public void accept(Throwable e) throws Exception {
                                Log.d(TAG, "accept: " + e.getLocalizedMessage());                            
                         }
                     }
        );
    }

我正在创建Reddit照片应用。我成功地调用了每个单独的请求,这意味着我的Retrofit接口正在工作。但是,我不知道如何使用zip运算符组合多个请求。运行代码后,我得到FATAL Exception: Main error

1 个答案:

答案 0 :(得分:0)

在您的apply函数中。您可以将objects数组强制转换为模型类类型。假设您的Retrofit界面如下所示:

 @GET("some")
 Observable<SubredditBody> getPics();

 @GET("some\more")
 Observable<SubredditBody> getEarthPorn();

// I have no idea what your the actual rest endpoints are but I'm assuming you 
// already have this portion down.

您可以遍历结果:

new Function<Object[], Object>() {
   @Override
   public Object apply(Object[] objects) throws Exception {                                            

        for (Object object : objects) {
             // Do something interesting here. This array has the result of your two API calls.
            if (object instanceOf SubredditBody) {
                SubredditBody body = (SubredditBody) object;
            }        
        }
        // Return your cool new object however you want. I didn't show how to 
        // instantiate this object but that's really up to you and your business
        // logic.
        return object;
    }
}

您在此签名中声明的第二种类型是您将在订阅中收到的类型,如下所示:

new Function<Object[], YourCoolNewType>() {
    ...
}).subscribe(new Consumer<YourCoolNewType>() {
    @Override
    public void accept(YourCoolNewType o) throws Exception {
         // Do something here
    }
});