比如下面这个方法:
public static Disposable subscribe(final Observable observable, final Consumer super H> onSuccess, final Consumer super Throwable> onError, final boolean showLoading) {
return observable.compose(handleErrors()).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable1 -> {
if (showLoading) {
DialogUtil.showLoading(AppUtil.getActivity());
}
})
.doFinally(() -> {
if (showLoading) {
DialogUtil.stopLoading(AppUtil.getActivity());
}
})
.subscribe(onSuccess, onError);
}
这是android app项目中的一个方法,且不管它是做什么的,我们来看下如何优化。
我们可以使用Builder模式来优化,代码如下:
public class RxSubscriberBuilder {
private final Observable observable;
private Consumer super T> onSuccess;
private Consumer super Throwable> onError;
private boolean showLoading = false;
private RxSubscriberBuilder(Observable observable) {
this.observable = observable;
}
public static RxSubscriberBuilder create(Observable observable) {
return new RxSubscriberBuilder(observable);
}
public RxSubscriberBuilder onSuccess(Consumer super T> onSuccess) {
this.onSuccess = onSuccess;
return this;
}
public RxSubscriberBuilder onError(Consumer super Throwable> onError) {
this.onError = onError;
return this;
}
public RxSubscriberBuilder showLoading(boolean showLoading) {
this.showLoading = showLoading;
return this;
}
public Disposable subscribe() {
return observable.compose(handleErrors()).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable1 -> {
if (showLoading) {
DialogUtil.showLoading(AppUtil.getActivity());
}
})
.doFinally(() -> {
if (showLoading) {
DialogUtil.stopLoading(AppUtil.getActivity());
}
})
.subscribe(onSuccess, onError);
}
private ObservableTransformer handleErrors() {
return upstream -> upstream.onErrorResumeNext((Throwable throwable) -> {
if (throwable instanceof AuthException) {
ToastUtils.show("登录失效");
}
return Observable.error(throwable);
});
}
}
使用:
RxSubscriberBuilder.create(api.getUser().toObservable())
.onSuccess(userDTO -> {})
.onError(throwable -> {})
.showLoading(true)
.subscribe();
我个人感觉方便了很多,比如我可能不需要传入onerror,使用建造者模式后可以选择不调用onerror即可,但如果是写成工具类,那就需要进行方法重载了 。一个简单的例子,希望对你有启发。
点赞,你的认可是我创作的动力 !
收藏,你的青睐是我努力的方向!
✏️评论,你的意见是我进步的财富!