一、AsyncSubject
Observer会接收AsyncSubject的onComplete()之前的最后一个数据。
AsyncSubject<String> asyncSubject = AsyncSubject.create();
asyncSubject.onNext("asyncSubject1");
asyncSubject.onNext("asyncSubject2");
asyncSubject.onComplete();
asyncSubject.subscribe(s -> System.out.println("asyncSubject: " + s));
结果:
asyncSubject: asyncSubject2
二、BehaviorSubject
Observer会先接收到 BehaviorSubject被订阅之前的最后一个数据, 再接收订阅之后发射过 来的数据。
BehaviorSubject<String> behaviorSubject = BehaviorSubject.create();
behaviorSubject.onNext("behaviorSubject1");
behaviorSubject.onNext("behaviorSubject2");
behaviorSubject.subscribe(s -> System.out.println("behaviorSubject: " + s));
behaviorSubject.onNext("behaviorSubject3");
behaviorSubject.onNext("behaviorSubject4");
behaviorSubject.onComplete();
结果:
behaviorSubject: behaviorSubject2
behaviorSubject: behaviorSubject3
behaviorSubject: behaviorSubject4
三、ReplaySubject
ReplaySubject 会发射所有来自原始 Observable 的数据 给观察者,无论它 们 是何时订阅的。
ReplaySubject<String> replaySubject = ReplaySubject.create();
replaySubject.onNext("replaySubject1");
replaySubject.onNext("replaySubject2");
replaySubject.subscribe(s -> System.out.println("replaySubject: " + s));
replaySubject.onNext("replaySubject3");
replaySubject.onNext("replaySubject4");
replaySubject.onComplete();
结果:
replaySubject: replaySubject1
replaySubject: replaySubject2
replaySubject: replaySubject3
replaySubject: replaySubject4
四、PublishSubject
Observer 只接收 PublishSubject 被订阅之后发送的数据。
PublishSubject<String> publishSubject = PublishSubject.create();
publishSubject.onNext("publishSubject1");
publishSubject.onNext("publishSubject2");
publishSubject.subscribe(s -> System.out.println("publishSubject" + s));
publishSubject.onNext("publishSubject3");
publishSubject.onNext("publishSubject4");
publishSubject.onComplete();
结果:
publishSubjectpublishSubject3
publishSubjectpublishSubject4
五、总结
AsyncSubject:不论订阅发生在什么时候,只发射最后一个数据。
BehaviorSubject:发送订阅之前的一个数据和订阅之后的全部数据。
ReplaySubject:不论订阅发生在什么时候,都发射全部数据。
PublishSubject:发送订阅之后全部数据。
网友评论