Rxjava解决android的请求接口的回调地狱

    Consumer consumer1 = new Consumer>>() {
        @Override
        public void accept(HttpResult> listHttpResult) throws Exception {
            Log.i("wangpanapan","----------------");
        }
    };
    Consumer comsumer2 = new Consumer>() {
        @Override
        public void accept(HttpResult userHttpResult) throws Exception {
            Log.i("wangpanapan","----------");
        }
    };
    /**
     * Schedulers.io() 代表io操作的线程, 通常用于网络,读写文件等io密集型的操作;
     Schedulers.computation() 代表CPU计算密集型的操作, 例如需要大量计算的操作;
     Schedulers.newThread() 代表一个常规的新线程;
     AndroidSchedulers.mainThread() 代表Android的主线程
     */
    public void loopRequest() {
        //定义被观察者
        Observable observable1 = RetrofitUtil.getNetApi().getGirls2()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        //定义被观察者
        final Observable observable2 = RetrofitUtil.getNetApi().addGirl("ACup",19)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

        observable1.doOnNext(consumer1).observeOn(Schedulers.io())
                .flatMap(new Function>,ObservableSource>>() {
                    @Override
                    public ObservableSource> apply(HttpResult> listHttpResult) throws Exception {
                        return observable2;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(comsumer2, new Consumer() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.i("wangpanapan","----------");
                    }
                });

你可能感兴趣的:(android)