RxJava:将来自不同Observables的项添加到Subject

时间:2018-03-05 12:06:02

标签: rx-java

我正在尝试向主题添加项目

但我无法拨打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()

2 个答案:

答案 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();

如果动态创建了源代码,请使用PublishSubjectmerge

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)

按合同规定,如果终止Subject subscribe()ObservableSubject也会终止。

您可以使用Relay而不是使用Subject。基本上是Subject,它不会从其来源传播终止。它实现了Consumer而不是Observer,但由于subscribe()接受其中任何一个接口作为类型参数RxRelay是替代品。