1. 程式人生 > >Rxjava解決android的請求介面的回撥地獄

Rxjava解決android的請求介面的回撥地獄

    Consumer consumer1 = new Consumer<HttpResult<List<User>>>() {
        @Override
        public void accept(HttpResult<List<User>> listHttpResult) throws Exception {
            Log.i("wangpanapan","----------------");
        }
    };
    Consumer comsumer2 = new Consumer<HttpResult<User>>() {
        @Override
        public void accept(HttpResult<User> 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<HttpResult<List<User>>,ObservableSource<HttpResult<User>>>() {
                    @Override
                    public ObservableSource<HttpResult<User>> apply(HttpResult<List<User>> listHttpResult) throws Exception {
                        return observable2;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(comsumer2, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.i("wangpanapan","----------");
                    }
                });