- Learning RxJava
- Thomas Nield
- 189字
- 2021-07-02 22:22:55
Using CompositeDisposable
If you have several subscriptions that need to be managed and disposed of, it can be helpful to use CompositeDisposable. It implements Disposable, but it internally holds a collection of disposables, which you can add to and then dispose all at once:
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import java.util.concurrent.TimeUnit;
public class Launcher {
private static final CompositeDisposable disposables
= new CompositeDisposable();
public static void main(String[] args) {
Observable<Long> seconds =
Observable.interval(1, TimeUnit.SECONDS);
//subscribe and capture disposables
Disposable disposable1 =
seconds.subscribe(l -> System.out.println("Observer 1: " +
l));
Disposable disposable2 =
seconds.subscribe(l -> System.out.println("Observer 2: " +
l));
//put both disposables into CompositeDisposable
disposables.addAll(disposable1, disposable2);
//sleep 5 seconds
sleep(5000);
//dispose all disposables
disposables.dispose();
//sleep 5 seconds to prove
//there are no more emissions
sleep(5000);
}
public static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
CompositeDisposable is a simple but helpful utility to maintain a collection of disposables that you can add to by calling add() or addAll(). When you no longer want these subscriptions, you can call dispose() to dispose of all of them at once.
推薦閱讀
- Advanced Machine Learning with Python
- OpenShift開發指南(原書第2版)
- Vue.js前端開發基礎與項目實戰
- Flink SQL與DataStream入門、進階與實戰
- Spring Boot+Spring Cloud+Vue+Element項目實戰:手把手教你開發權限管理系統
- 用Flutter極速構建原生應用
- Drupal 8 Configuration Management
- Getting Started with Greenplum for Big Data Analytics
- Access 2010數據庫應用技術(第2版)
- Mastering Linux Security and Hardening
- 基于SpringBoot實現:Java分布式中間件開發入門與實戰
- 機器學習微積分一本通(Python版)
- Extending Unity with Editor Scripting
- QPanda量子計算編程
- Android 游戲開發大全(第二版)