zoukankan      html  css  js  c++  java
  • RxJava的四种Subjects:PublishSubject、ReplaySubject、BehaviorSubject、AsyncSubject的理解

    Subject:它既是Observable,又是observer。也就是既可以发送事件,也可以接收事件。

    下面是四个子类PublishSubject、ReplaySubject、BehaviorSubject、AsyncSubject的区别:

    PublishSubject<Integer> source = PublishSubject.create();  //PublicSubject:接收到订阅之后的所有数据。
    // It will get 1, 2, 3, 4 and onComplete
    source.subscribe(getFirstObserver()); 
    source.onNext(1);
    source.onNext(2);
    source.onNext(3);
    // It will get 4 and onComplete for second observer also.
    source.subscribe(getSecondObserver());
    source.onNext(4);
    source.onComplete();
    ReplaySubject<Integer> source = ReplaySubject.create();  //ReplaySubject:接收到所有的数据,包括订阅之前的所有数据和订阅之后的所有数据。
    // It will get 1, 2, 3, 4
    source.subscribe(getFirstObserver());
    source.onNext(1);
    source.onNext(2);
    source.onNext(3);
    source.onNext(4);
    source.onComplete();
    // It will also get 1, 2, 3, 4 as we have used replay Subject
    source.subscribe(getSecondObserver());
    BehaviorSubject<Integer> source = BehaviorSubject.create();  //BehaviorSubject:接收到订阅前的最后一条数据和订阅后的所有数据。
    // It will get 1, 2, 3, 4 and onComplete
    source.subscribe(getFirstObserver());
    source.onNext(1);
    source.onNext(2);
    source.onNext(3);
    // It will get 3(last emitted)and 4(subsequent item) and onComplete
    source.subscribe(getSecondObserver());
    source.onNext(4);
    source.onComplete();
    AsyncSubject<Integer> source = AsyncSubject.create();  //AsyncSubject:不管在什么位置订阅,都只接接收到最后一条数据
    // It will get only 4 and onComplete
    source.subscribe(getFirstObserver());
    source.onNext(1);
    source.onNext(2);
    source.onNext(3);
    // It will also get only get 4 and onComplete
    source.subscribe(getSecondObserver());
    source.onNext(4);
    source.onComplete();
  • 相关阅读:
    服务器模型??
    tcp和udp详解??
    osi七层模型??
    高内聚 低耦合??
    进程和线程的区别和联系??
    2019.10.03题解
    2019.10.02题解
    2019.09.29考试报告
    2019.09.27考试报告
    2019.09.26考试报告
  • 原文地址:https://www.cnblogs.com/yongfengnice/p/10229473.html
Copyright © 2011-2022 走看看