我很难理解RX。在下列情况下,是否有必要取消订阅?有没有办法在"电话"之后自动取消订阅?功能被执行了?
Observable.create(new Observable.OnSubscribe<NumberInfo>() {
@Override
public void call(Subscriber<? super NumberInfo> subscriber) {
try {
// Store data to db
} catch (Exception e) {
Log.e(TAG, "Downloaded numberInfo was not added to cache.", e);
}
}
}).subscribeOn(Schedulers.newThread())
.subscribe();
我不想观察任何结果,这就是为什么我省略了经典.observeOn(AndroidSchedulers.mainThread())
感谢解释。
答案 0 :(得分:5)
根据Rx合约,当Observable
触发onCompleted
时,Observer
取消订阅。在您的情况下,合同不受尊重,因为您的代码中没有subscriber.onCompleted()
。
如果你只需要像#34; Fire and forget&#34;那么你可以试试:
Schedulers.io().createWorker().schedule(new Action0() {
@Override
public void call() {
try {
// Store data to db
} catch (Exception e) {
Log.e(TAG, "Downloaded numberInfo was not added to cache.", e);
}
}
});
它将在 I / O 计划程序上执行,您的UI线程是安全的。
IMO你应该总是有一个返回值。您的Store data to db
路由肯定会有一些返回值,例如long
指定行号或boolean
表示成功。有了这种方法,您就可以创建一个合适的方法:
public Observable<Long> storeToDb(final SomethingToStore storeMe) {
return Observable
.create(new Observable.OnSubscribe<Long>() {
@Override
public void call(Subscriber<? super Long> subscriber) {
long row = syncStore(storeMe);
if (row == -1) {
subscriber.onError(new Throwable("Cannot store " + storeMe.toString + " to DB."));
}
subscriber.onNext(row);
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
你可以像这样使用它:
storeToDb(storeThis)
.subscribe(new Observer<Long>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e("STORING", "Something went south: " + e.getMessage());
}
@Override
public void onNext(Long row) {
Log.d("STORING", "Everything has been stored as record number: " + row);
}
});