我有時必須在Observable中執行一些清理任務(例如關閉打開的文件),我想知道什麼是最好的方法。 到目前爲止,我已經看到了兩個,但我很難理解它們有什麼不同:你能解釋一下這些差異嗎?是否有更好的方法來實現這一點?RxJava Observable.doOnUnsubscribe()vs Subscriber.add()
1)
// MyObject will take care of calling onNext(), onError() and onCompleted()
// on the subscriber.
final MyObject o = new MyObject();
Observable obs = Observable.create(new Observable.OnSubscribe<Object>() {
@Override
public void call(Subscriber<? super Object> subscriber) {
try {
if (!subscriber.isUnsubscribed()) {
o.setSubscriber(subscriber);
// This will tell MyObject to start allocating resources and do its job.
o.start();
}
} catch (Exception e) {
subscriber.onError(e);
}
}
}).doOnUnsubscribe(new Action0() {
@Override
public void call() {
// This will tell MyObject to finish its job and deallocate any resources.
o.stop();
}
});
2)
Observable obs = Observable.create(new Observable.OnSubscribe<Object>() {
@Override
public void call(Subscriber<? super Object> subscriber) {
try {
if (!subscriber.isUnsubscribed()) {
// MyObject will take care of calling onNext(), onError() and onCompleted()
// on the subscriber.
final MyObject o = new MyObject(subscriber);
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
// This will tell MyObject to finish its job and deallocate any resources.
o.stop();
}
}));
// This will tell MyObject to start allocating resources and do its job.
o.start();
}
} catch (Exception e) {
subscriber.onError(e);
}
}
});
您已經使用'doOnSubscribe資源'在示例1中。它應該是問題標題中提到的'doOnUnsubscribe'。 –
@PraveerGupta謝謝我修復了錯字! –