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

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.

主站蜘蛛池模板: 四平市| 玉溪市| 萝北县| 江孜县| 延安市| 仲巴县| 巴里| 屏山县| 阿勒泰市| 芒康县| 格尔木市| 板桥市| 从化市| 北安市| 合作市| 黑山县| 虹口区| 富蕴县| 淮北市| 会宁县| 张掖市| 梁山县| 宁津县| 中西区| 分宜县| 文安县| 招远市| 利辛县| 游戏| 永修县| 南宁市| 昌图县| 库伦旗| 南川市| 尚志市| 项城市| 文化| 永仁县| 大姚县| 双江| 万全县|