我使用RxJava来观察多个源,然后根据Observables的值执行操作。我想知道它是否可以进一步简化。
目标: 完整实现RxJava。
我拥有的: 1. Room(数据库ORM),用于使用RxJava存储本地数据库。 2.使用RxJava进行Retrofit的WebService API。
条件: 1.定期运行Webservice呼叫。 2. Webservice调用执行取决于从数据库检索的数据的结果。
代码:
Dao class
@Query("select * from Login")
Flowable<List<Login>> getLoginRx();
API类
@Multipart
@POST("..")
Flowable<NotificationResponse> notification();
Java类
private Subscriber<List<Login>> loginSubscriber;
private Subscriber<NotificationResponse> notifSubscriber;
private Observer<Long> timerObserver;
private RoomDb roomDb;
@Override
protected void onCreate(Bundle b){
roomDb = RoomDb.getInstance(this);
notifSubscriber = new Subscriber<NotificationResponse>() {
@Override
public void onSubscribe(Subscription s) {
s.request(1);
notifSubscription = s;
}
@Override
public void onNext(NotificationResponse nr) {
if (nr.getSuccess()) {
if (NetworkClient.STATUS_OK.equals(nr.getData().getStatus())) {
updateCounts(nr.getData());
}
}
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
};
timerObserver = new Observer<Long>() {
@Override
public void onSubscribe(Disposable d) {
networkCallRepeat = d;
}
@Override
public void onNext(Long aLong) {
NetworkClient.getInstance(MainActivity.this).getNetworkAPI().notification(NetworkClient.stringPart(NetworkAPI.STAFF_TOKEN))
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(notifSubscriber);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
};
loginSubscriber = new Subscriber<List<Login>>() {
@Override
public void onSubscribe(Subscription s) {
s.request(1);
loginSubscription = s;
}
@Override
public void onNext(List<Login> logins) {
if (logins != null && logins.size() > 0) {
updateLoginState(logins.get(0));
Observable
.interval(0L, 1L, TimeUnit.MINUTES)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(timerObserver);
} else {
if (networkCallRepeat != null && !networkCallRepeat.isDisposed()) {
networkCallRepeat.dispose();
}
updateLoginState(null);
}
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
};
}
@Override
protected void onResume() {
super.onResume();
roomDb.loginDao().getLoginRx()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(loginSubscriber);
}