我是RxJava的超级大三学生,如果我选择了一种糟糕的方法或者有更好的方法,我需要帮助才能找到更好的方法。
我正在处理遗留的Loader
代码,我想用RxJava替换它。
我跟随我的原始代码:
public class CurrentBookingLoaderManager extends AsyncTaskLoader<Booking> {
...
@Override
public Booking loadInBackground() {
try {
return createPendingBookingObserver().blockingGet(); // Gets last Booking from back-end
} catch (Exception e) {
Logger.logCaughtException(e);
return loadPendingBookingFromDB();
}
}
private Single<Booking> createPendingBookingObserver() {...}
private Booking loadPendingBookingFromDB() {...}
}
因此,我的Presenter课程正在寻找最新的预订对象,以便将用户引导至下一个屏幕(基于预订状态)。
final class Presenter {
void findLatestBooking() {
CurrentBookingLoaderManager.newInstance(mContext)
.getPendingBooking(mActivity, new CurrentBookingLoaderManager.OnPendingBooking() {
@Override
public void found(Booking booking) {
...
}
});
}
}
回到CurrentBookingLoaderManager
,我创建了一个接口和几个方法,以便以Rx方式重构loadInBackground()
的功能。
public interface OnPendingBooking {
void found(Booking booking);
}
public void getPendingBooking(final MyActivity activity, final OnPendingBooking callback) {
CurrentBookingLoaderManager.newInstance(activity)
.createPendingBookingObserver()
.compose(activity.<Booking>asyncCallWithinLifecycle())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Booking>() {
@Override
public void accept(Booking booking) throws Exception {
callback.found(booking);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
loadPendingBookingFromDB(activity, callback);
}
});
}
private void loadPendingBookingFromDB(final MyActivity activity, final OnPendingBooking callback) {
Single.fromCallable(new Callable<Booking>() {
@Override
public Booking call() throws Exception {
return loadPendingBookingFromDB();
}
})
.compose(activity.<Booking>asyncCallWithinLifecycle())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Booking>() {
@Override
public void accept(Booking booking) throws Exception {
callback.found(booking);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
callback.found(null);
}
});
}
让我觉得这种方法不正确的方法是使用RxJava有很多行,而Rx通常会减少代码行数。所以,如果您认为有更好的方法,请给我一些指示。
根据我的测试,此代码可以正常工作。
答案 0 :(得分:1)
subscribeOn(Schedulers.newThread())
- &gt; subscribeOn(Schedulers.io())
(无需每次都创建新主题)和
Observable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
可以替换为
public class RxUtil {
public static <T> Observable.Transformer<T, T> applySchedulers() {
return observable -> observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
}
和
Observable
.compose(RxUtil::applySchedulers)