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

  • 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.

主站蜘蛛池模板: 河北区| 舟山市| 丹巴县| 盐山县| 绥宁县| 萨嘎县| 临汾市| 静乐县| 邵东县| 陇川县| 隆德县| 睢宁县| 新泰市| 望谟县| 名山县| 蒲城县| 曲松县| 仁布县| 丁青县| 余庆县| 东方市| 闽清县| 光山县| 星子县| 巴里| 普兰店市| 来凤县| 兰西县| 遵化市| 富宁县| 遵化市| 来安县| 延吉市| 柘城县| 宁蒗| 兰考县| 尼勒克县| 宝坻区| 京山县| 荃湾区| 清水河县|