同时请求多个REST API

时间:2019-03-06 11:28:40

标签: android rx-android

我的目的是与Retrofit同时请求双重REST API,他们的回应是List。我想处理每个响应以更新到View(响应1正常-> View1显示数据,response2错误-> View2显示错误)。我该如何使用RxAndroid?

3 个答案:

答案 0 :(得分:1)

首先,您需要使用RxAdapter作为改造适配器工厂进行改造,然后每个请求应返回Observable

注册RXAdapter进行改装

<TableBody>
{
    (this.props.data)
        ? this.props.data.map((item, i) => (
            return (
                <TableRow key={i}>
                    <TableCell align="right">
                    {
                        (item.validationMessage.errors[0].length > 0)
                            ? item.validationMessage.errors[0].errorMessage
                            : ''
                    }
                    </TableCell>                                                                                                                       
                    <TableCell align="right">{item.partNumber}</TableCell>
                    <TableCell align="right">{item.description}</TableCell>
                    <TableCell align="right">{item.partCategoryId}</TableCell>
                    <TableCell align="right">{item.oemPartNumber}</TableCell>
                </TableRow>
            );
        ))
        : ''
}

之后,在改造中,ApiInterface应该返回observable,例如,说要获取用户列表和课程列表

new Retrofit.Builder()
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

之后,在演示者中或您处理逻辑的任何地方,都需要订阅

@GET("users")
Observable<List<User>> getUsers();
@GET("courses")
Observable<List<Course>> getCourses();

答案 1 :(得分:0)

您可以多次调用它,因为它是使用Square的翻新版进行的异步回调

public void Prepare_Review_data() {
    try {
        if (token != null) {
            if (isConnected()) try {
                loading = ProgressHUD.show(getContext(), "Loading Reviews", true, false, Heizolscout_Reviews.this);
                Call<JsonElement> call = apiService.Heizolscout_Reviews("Bearer " + token.getAccessToken());
                call.enqueue(new Callback<JsonElement>() {
                    @Override
                    public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                        Log.d("History Information", response.toString());
                        loading.dismiss();
                        if (response.code() == 401) {
                            Fragment frag = new Heizolscout_Login();
                            if (frag != null) {
                                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                                FragmentTransaction ft = fragmentManager.beginTransaction();
                                ft.replace(R.id.sacreenarea, frag);
                                ft.commit();
                            }
                        } else if (response.code() == 200) {
                            try {
                                Gson gson = new Gson();
                                Type listType = new TypeToken<List<Review_Model>>(){}.getType();
                                ArrayList<Review_Model>noti = gson.fromJson(response.body(), listType);
                                Log.d("Notification success",Review_models.size()+"");
                                if (noti.size()>0){
                                    for (Review_Model n:noti){
                                        Review_models.add(n);
                                    }
                                    Review_Adapter.notifyDataSetChanged();
                                }else {
                                    Toast.makeText(getActivity(),getString(R.string.review_no_list_string), Toast.LENGTH_LONG).show();
                                }
                                Review_Adapter.notifyDataSetChanged();
                            } catch (Exception e) {
                                Log.d("Error Line Number", Log.getStackTraceString(e));
                            }
                            try {
                                Log.d("History error", response.body().getAsJsonObject().get("error").toString());
                                if (!response.body().getAsJsonObject().get("error").isJsonNull()) {
                                    Show_Alert(getString(R.string.open_email), response.body().getAsJsonObject().get("error").toString(), getString(R.string.ok), getString(R.string.normal));
                                }
                            } catch (Exception e) {
                                Log.d("Error Line Number", Log.getStackTraceString(e));
                            }
                        } else if (response.code() == 422) {
                            Show_Alert(getString(R.string.invalid_tittle), getString(R.string.invalid_tittle_details), getString(R.string.ok), getString(R.string.normal));
                        } else {
                            Show_Alert(getString(R.string.error_tittle), getString(R.string.error_tittle_details), getString(R.string.ok), getString(R.string.normal));
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonElement> call, Throwable t) {
                        // Log error here since request failed
                        Log.e("Error", t.toString());
                        Show_Alert(getString(R.string.error_tittle), getString(R.string.error_tittle_details), getString(R.string.ok), getString(R.string.normal));
                        loading.dismiss();
                    }
                });
            } catch (Exception e) {
                loading.dismiss();
                Log.d("Error Line Number", Log.getStackTraceString(e));
            }
            else {
                Show_Alert(getString(R.string.internet_tittle), getString(R.string.internet_details), getString(R.string.ok), getString(R.string.nointernet));
            }
        } else {
            Fragment frag = new Heizolscout_Login();
            if (frag != null) {
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.replace(R.id.sacreenarea, frag);
                ft.commit();
            }
        }
    } catch (Exception e) {
        Log.d("Error Line Number", Log.getStackTraceString(e));
    }
}

答案 2 :(得分:0)

一种方法是使用Observable.zip()

在您的情况下,将是这样的:

Observable.zip( request1, request2.doOnError(//show error here), BiFunction<response1,response2, combinedResponses>{response1, response2 -> new CombinedResponses(response1, response2)}).subscribe(new Observer{...})

如果您需要更多信息,可以随时查看documentation