- Learning RxJava
- Thomas Nield
- 159字
- 2021-07-02 22:22:55
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));
});
}
- Node.js+Webpack開發實戰
- CockroachDB權威指南
- Oracle Database In-Memory(架構與實踐)
- Ray分布式機器學習:利用Ray進行大模型的數據處理、訓練、推理和部署
- Elasticsearch for Hadoop
- Hands-On Automation Testing with Java for Beginners
- Python深度學習:基于TensorFlow
- PHP編程基礎與實例教程
- Learning jQuery(Fourth Edition)
- Angular應用程序開發指南
- Qt 4開發實踐
- Hands-On Dependency Injection in Go
- Android初級應用開發
- MongoDB Cookbook
- SQL Server 2008實用教程(第3版)