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

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.

主站蜘蛛池模板: 溆浦县| 微博| 福安市| 浠水县| 汝南县| 托里县| 腾冲县| 永昌县| 堆龙德庆县| 保德县| 邳州市| 武强县| 玉田县| 民丰县| 内江市| 綦江县| 盘山县| 全椒县| 新乐市| 洛浦县| 武陟县| 漾濞| 东阿县| 互助| 明光市| 永顺县| 平南县| 襄垣县| 德安县| 高安市| 富民县| 左云县| 辽宁省| 兴宁市| 贡嘎县| 北川| 大宁县| 井陉县| 河东区| 绥中县| 友谊县|