我正在尝试向主题添加项目
但我无法拨打Subject.onNext()
,因为我从其他Observables
// My observer subscribes to a ReplaySubject
subject.subscribe(observer)
// The first item is emitted (and regularly received by my observer)
// by the first observable, that after that terminates
firstObservable.subscribeWith(subject)
// Now I have other observables emitting other things,
// and I would like to send them to the subject so that the observer receives them,
// possibly without manually calling subject.onNext()
答案 0 :(得分:1)
不建议将Subject
订阅到多个Observable
,但您可以合并这些Observable
并订阅:{/ p>
ReplaySubject<Integer> subject = ReplaySubject.create();
Observable.merge(first, second, third).subscribe(subject);
但是,您可以通过replay()
和autoConnect()
实现类似的缓存效果:
Observable<Integer> cached =
Observable.merge(first, second, third).replay().autoConnect();
如果动态创建了源代码,请使用PublishSubject
和merge
:
Subject<Observable<Integer>> sources = PublishSubject.<Observable<Integer>>.create()
.toSerialized();
Observable<Integer> output = Observable.merge(sources).replay().autoConnect();
sources.onNext(Observable.fromCallable(() -> getOneThing()));
sources.onNext(Observable.range(1, 10).subscribeOn(Schedulers.computation()));
答案 1 :(得分:0)