我有2张桌子TimeStamps和Infraction,我想做 类似于使用Rx Android改造的东西:
Request-> I get TimeStamps (if it's changed)
-> I send new request to get Infractions
else I display infractions from database
这就是我使用Retrofit所做的,是正确的吗?
Observable<TimeStamps> callTimeStamp = apiInterface.getTimeStamp();
TimeStamps stamps = realm.where(TimeStamps.class).findFirst();
callTimeStamp.flatMap(new Function<TimeStamps, ObservableSource<List<Infraction>>>() {
@Override
public ObservableSource<List<Infraction>> apply(TimeStamps timeStamps) throws Exception {
if(!timeStamps.getInfractionTimeStamps().equalsIgnoreCase( stamps.getInfractionTimeStamps()))
return apiInterface.getInfractions();
else
return null;
}
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<Infraction>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(List<Infraction> infractions) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
答案 0 :(得分:1)
没有
TimeStamps stamps = realm.where(TimeStamps.class).findFirst();
这在当前线程上获得stamps
if(!timeStamps.getInfractionTimeStamps()。equalsIgnoreCase( stamps.getInfractionTimeStamps()))
这会尝试访问另一个线程上的stamps
实例,因此您将获得IllegalStateException
返回null;
即使它确实有效,这一行也会使RxJava2抛出NullPointerException
.subscribeOn(Schedulers.newThread())
这可能很容易Schedulers.io()
,因此它不会创建太多线程(当然,你应该确保使用try(Realm realm = ...)
或finally { realm.close() }
)
.subscribe(new Observer&gt;(){
这是错误的,除非你&#34;正确实施onSubscribe&#34;这根本不是预期的,应该是new DisposableObserver<List<Infraction>>()
。
在这种情况下,您的Retrofit界面可能会公开Single<T>
,因为单身会在完成后自动取消订阅。
Single<TimeStamps> callTimeStamp = apiInterface.getTimeStamp();
callTimeStamp.flatMap((timeStamps) -> {
try(Realm realm = Realm.getDefaultInstance()) {
TimeStamps stamps = realm.where(TimeStamps.class).findFirst();
if(!timeStamps.getInfractionTimeStamps().equalsIgnoreCase( stamps.getInfractionTimeStamps()))
return apiInterface.getInfractions();
else
return Single.never();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableObserver<List<Infraction>>() {
@Override
public void onNext(List<Infraction> infractions) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});