RxJava和Retrofit2:android.os.NetworkOnMainThreadException

时间:2016-08-29 15:09:42

标签: android rx-java retrofit2

我尝试在Observable.zip(...)中组合几个请求,但是我收到了一个错误android.os.NetworkOnMainThreadException。我做错了什么?

Call<EmployeeInfo> companyInfo = apiService.employee();
    companyInfo.enqueue(new Callback<EmployeeInfo>() {
        @Override
        public void onResponse(Call<EmployeeInfo> call, Response<EmployeeInfo> response) {
            EmployeeInfo info = response.body();
            Observable.zip(
                    apiService.getOrders("https://exaple.com"),
                    apiService.getOrders("https://exaple.com"),
                    apiService.getOrders("https://exaple.com"),
                    apiService.companyInfo("1"), new Func4<Orders, Orders, Orders, CompanyInfo, OrdersDataWrapper>() {
                        @Override
                        public OrdersDataWrapper call(Orders currentOrders, Orders waitingOrders, Orders enterOrders, CompanyInfo companyInfo) {
                            OrdersDataWrapper data = new OrdersDataWrapper();
                            return data;
                        }
                    }).onErrorReturn(new Func1<Throwable, OrdersDataWrapper>() {
                @Override
                public OrdersDataWrapper call(Throwable throwable) {
                    return null;
                }
            })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<OrdersDataWrapper>() {
                        @Override
                        public void call(OrdersDataWrapper alDataWrapper) {
                        }
                    });
        }

        @Override
        public void onFailure(Call<EmployeeInfo> call, Throwable t) {
        }
    });

1 个答案:

答案 0 :(得分:3)

您正在设置.observeOn,但不设置.subscribeOn,因此RxJava正在订阅并观察主线程。添加.subscribeOn(Schedulers.io()),以便在后台线程上执行调用。