rxjava : 常用的 compose 与 ObservableTransformer

RxJavaUtils 工具类

public class RxJavaUtils {

    public static  ObservableTransformer applySchedulers() {
        return new ObservableTransformer() {
            @Override
            public ObservableSource apply(Observable upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    public static ObservableTransformer, Boolean> checkSuccessCode() {
        return new ObservableTransformer, Boolean>() {
            @Override
            public ObservableSource apply(Observable> upstream) {
                return upstream.map(new Function, Boolean>() {
                    @Override
                    public Boolean apply(Response response) throws Exception {
                        return response != null && response.code() == 204;
                    }
                });
            }
        };
    }

    public static  ObservableTransformer preventDuplicateClicks(long interval) {
        return new ObservableTransformer() {
            @Override
            public ObservableSource apply(Observable upstream) {
                return upstream.throttleFirst(interval, TimeUnit.MILLISECONDS);
            }
        };
    }

    //lambda简化版

//    public static  ObservableTransformer applySchedulers() {
//        return upstream -> upstream.subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread());
//    }
//
//    public static ObservableTransformer, Boolean> checkSuccessCode() {
//        return upstream -> upstream.map((Function, Boolean>)
//                response -> response != null && response.code() == 204);
//    }
//
//    public static  ObservableTransformer preventDuplicateClicks(long interval) {
//        return upstream -> upstream.throttleFirst(interval, TimeUnit.MILLISECONDS);
//    }

}

测试:

Disposable disposable = Observable.just(1, 2, 3)
    .compose(RxJavaUtils.applySchedulers())
    .compose(RxJavaUtils.preventDuplicateClicks(1000))
    .subscribe(integer -> {

    });

你可能感兴趣的:(rxjava)