我正在敲定关于RxJava的一些文档,我意识到我有一个问题。为什么我们甚至需要BehaviorSubject
,ASyncSubject
和ReplaySubject
?我们不能只使用PublishSubject
并使用正确的运算符来创建这些行为吗?
例如,BehaviorSubject
似乎可以使用replay(1).autoConnect()
进行复制。我认为您可以或多或少地使用运算符来完成其他主题的策略,使用replay(1).autoConnect().take(1)
ASyncSubject
,cache()
ReplaySubject
import io.reactivex.Observable;
import io.reactivex.subjects.AsyncSubject;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.Subject;
public class Launcher {
public static void main(String[] args) {
Subject<String> subject =
BehaviorSubject.<String>create().toSerialized();
Observable<String> cacheLast =
subject.replay(1).autoConnect();
cacheLast.subscribe(s -> System.out.println("Observer 1: " + s));
subject.onNext("Alpha");
subject.onNext("Beta");
subject.onNext("Gamma");
cacheLast.subscribe(s -> System.out.println("Observer 2: " + s));
}
}
。
Sht As Worksheet