美文网首页android基础知识
利用RxJava替换嵌套接口回调

利用RxJava替换嵌套接口回调

作者: suikaJY | 来源:发表于2018-06-26 09:00 被阅读184次

    RxJava替换嵌套接口回调

    有时项目中需要进行两次或者三次以上的接口访问,这时如果使用同步方式走接口就需要实现嵌套的接口回调

    传统方式的代码是如下实现的:

    1. 定义回调接口
        public interface Callback {
            void onSuccess(Object result);
    
            void onFail(Exception e);
        }
    
    1. 封装两个接口的访问
        //第一次接口访问
        public void firstApi(Callback callback) {
            Request request = new Request.Builder().url("http://www.example1.com").build();
            new OkHttpClient().newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    callback.onFail(e);
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        byte[] bytes = response.body().bytes();
                        if (bytes != null) {
                            callback.onSuccess(bytes);
                        }
                    } else {
                        callback.onFail(new IllegalStateException("response code is not 200"));
                    }
                }
            });
        }
    
        //第二次接口访问
        public void secondApi(Callback callback) {
            Request request = new Request.Builder().url("http://www.example2.com").build();
            new OkHttpClient().newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    callback.onFail(e);
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String jsonString = response.body().string();
                        callback.onSuccess(jsonString);
                    } else {
                        callback.onFail(new IllegalStateException("response code is not 200"));
                    }
                }
            });
        }
    
    1. 使用时会造成嵌套接口回调
        public void test() {
            firstApi(new Callback() {
                @Override
                public void onSuccess(Object result) {
                    secondApi(new Callback() {
                        @Override
                        public void onSuccess(Object result) {
                            //do something...
                        }
    
                        @Override
                        public void onFail(Exception e) {
    
                        }
                    });
                }
    
                @Override
                public void onFail(Exception e) {
    
                }
            });
        }
    

    像这样的回调两个还行,三个以上根本没法看

    改用RxJava的方式

    • 主要是利用flatMap切换Observable来替换被观察主题
    • 每次嵌套就调用一次flatMap
    /**
     * @author zjy
     * @date 2018/6/25
     */
    public class RxJavaTestActivity extends AppCompatActivity {
    
        private TextView mTvInfo;
    
        public static void start(Context context) {
            Intent intent = new Intent(context, RxJavaTestActivity.class);
            context.startActivity(intent);
        }
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_rx_test);
            mTvInfo = findViewById(R.id.tv_info);
        }
    
        @SuppressLint("CheckResult")
        public void onTest(View view) {
            firstFun()
                    .flatMap((Function<String, ObservableSource<String>>) this::secondFun)//核心方法:利用flatMap操作符更换数据提供者(也就是被观察者Observable)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(s -> mTvInfo.append("accept result: " + s));
        }
    
        //第一层接口回调
        public Observable<String> firstFun() {
            return Observable.create(emitter -> new Thread(() -> {
                //模仿异步访问接口
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                final String result = "first observable class\n";
                runOnUiThread(() -> mTvInfo.append("first result: " + result));
                emitter.onNext(result);
                emitter.onComplete();
            }).start());
        }
    
        //第二层接口回调
        public Observable<String> secondFun(String param) {
            return Observable.create((ObservableEmitter<String> emitter) -> new Thread(() -> {
                //模仿异步访问接口
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                final String result = "second observable class\n";
                runOnUiThread(() -> {
                    mTvInfo.append("second: upstream param \"" + param + "\"");
                    mTvInfo.append("second result: " + result);
                });
                emitter.onNext(result);
                emitter.onComplete();
            }).start());
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:利用RxJava替换嵌套接口回调

        本文链接:https://www.haomeiwen.com/subject/smhpyftx.html