官术网_书友最值得收藏!

Handling Disposal with Observable.create()

If your Observable.create() is returning a long-running or infinite Observable, you should ideally check the isDisposed() method of ObservableEmitter regularly, to see whether you should keep sending emissions. This prevents unnecessary work from being done if the subscription is no longer active.

In this case, you should use Observable.range(), but for the sake of the example, let's say we are emitting integers in a for loop in Observable.create(). Before emitting each integer, you should make sure that ObservableEmitter does not indicate that a disposal was called:

    import io.reactivex.Observable;

public class Launcher {
public static void main(String[] args) {
Observable<Integer> source =
Observable.create(observableEmitter -> {
try {
for (int i = 0; i < 1000; i++) {
while (!observableEmitter.isDisposed()) {
observableEmitter.onNext(i);
}
if (observableEmitter.isDisposed())
return;
}
observableEmitter.onComplete();
} catch (Throwable e) {
observableEmitter.onError(e);
}
});
}
}

If your Observable.create() is wrapped around some resource, you should also handle the disposal of that resource to prevent leaks. ObservableEmitter has the setCancellable() and setDisposable() methods for that. In our earlier JavaFX example, we should remove the  ChangeListener from our JavaFX ObservableValue when a disposal occurs. We can provide a lambda to setCancellable(), which will execute the following action for us, which will occur when dispose() is called:

    private static <T> Observable<T> valuesOf(final ObservableValue<T> 
fxObservable) {
return Observable.create(observableEmitter -> {

//emit initial state
observableEmitter.onNext(fxObservable.getValue());

//emit value changes uses a listener
final ChangeListener<T> listener =
(observableValue, prev, current) ->
observableEmitter.onNext(current);

//add listener to ObservableValue
fxObservable.addListener(listener);

//Handle disposing by specifying cancellable
observableEmitter.setCancellable(() ->
fxObservable.removeListener(listener));
});
}
主站蜘蛛池模板: 东光县| 肥东县| 天祝| 和静县| 新巴尔虎右旗| 连云港市| 崇义县| 扎兰屯市| 房山区| 蒙山县| 阿拉善右旗| 朝阳区| 罗田县| 平遥县| 小金县| 玉环县| 梁河县| 若羌县| 卢龙县| 台北县| 灵丘县| 兖州市| 广平县| 额济纳旗| 绥化市| 广丰县| 巴南区| 永吉县| 洮南市| 白沙| 夏津县| 萝北县| 杨浦区| 涿鹿县| 寿光市| 福鼎市| 泰兴市| 长乐市| 苗栗市| 西充县| 漯河市|