RxSchedulersHelper

提供两个功能

1.线程切换操作

2.网络加载弹出对话框(Loading Dialog),加载完成后Loading Dialog 消失(dismiss)

3.特别注意doOnNext()方法的回调,仅仅支持一个onNext,当Observable发射的数据是List的时候,第一次回调onNext的时候,对话框就会消失

代码如下:

public class RxSchedulersHelper {

    public static  Observable.Transformer io_main() {
        return new Observable.Transformer() {
            @Override
            public Observable call(Observable tObservable) {
                return tObservable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    public static  Observable.Transformer io_main_loading_dialog(@NonNull Context context) {
        final Dialog loadingDialog = new Dialog(context);
        return new Observable.Transformer() {
            @Override
            public Observable call(Observable tObservable) {
                return tObservable
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                if (Looper.myLooper() == Looper.getMainLooper()) {
                                    loadingDialog.show();
                                }
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                          .doOnNext(new Action1() {
                            @Override
                            public void call(T t) {
                                if (Looper.myLooper() == Looper.getMainLooper()) {
                                    //MainThread
                                    loadingDialog.dismiss();
                                }
                            }
                        })
                        .doOnError(new Action1() {
                            @Override
                            public void call(Throwable throwable) {
                                if (Looper.myLooper() == Looper.getMainLooper()) {
                                    //MainThread
                                    loadingDialog.dismiss();
                                }
                            }
                        })
                        .doOnTerminate(new Action0() {
                            @Override
                            public void call() {
                                if (Looper.myLooper() == Looper.getMainLooper()) {
                                    //MainThread
                                    loadingDialog.dismiss();
                                }
                            }
                        });
            }
        };
    }


}

你可能感兴趣的:(RxSchedulersHelper)