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

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

主站蜘蛛池模板: 兰溪市| 来宾市| 东港市| 华安县| 兰西县| 朝阳区| 永和县| 京山县| 应用必备| 日土县| 郯城县| 锦州市| 凭祥市| 吴桥县| 梁河县| 桐乡市| 洱源县| 沙田区| 宣化县| 阳曲县| 牙克石市| 嘉鱼县| 百色市| 陕西省| 商丘市| 盐源县| 迁西县| 南皮县| 东乡族自治县| 息烽县| 门源| 天镇县| 宁蒗| 上林县| 原阳县| 黑河市| 同仁县| 堆龙德庆县| 旬邑县| 凤庆县| 万宁市|