1
votes

I would like to have the result of multiple observables combined into a parent observable. I don't have access to all the observables at once, they will be subscribed throughout the execution of the program.

So far this was my approach:

...
compoundObservable = compoundObservable.mergeWith(firstObservable);
...
compoundObservable = compoundObservable.mergeWith(secondObservable);
...

The approach hasn't worked, as the events sent by the otherObservable aren't registered by the subscribers of the compoundObservable.

How can I combine these observables?

2
would using a Subject be an option in your case? - Lamorak
So, firstObservable and secondObservable will be created only after someone has subscribed to (what was then) compoundOversable? - david.mihola
firstObservable and secondObservable have already been created. I'm looking to accumulate the result of each observable in the compoundObservable. As for a Subject I'm open to it - post an answer! - bkach
OK, but when are you subscribing to compoundObservable? The crucial point is that all Observables are immutable: mergeWith returns a new instance that's different from the previous value of compoundObservable, even though you're using the same variable name to keep it. The main point is: You'd have to merge(With) before subscribing - if you merge afterwards you'll just never use the merged Observable. - david.mihola

2 Answers

3
votes

Using a Subject you can subscribe to observables at any time and all the subscribers of the subject will get all the items. This can be a bit tricky when debugging, though.

PublishSubject<Object> subject = PublishSubject.create();
Observable<Object> observable1 = ...;
observable1.subscribe(subject);

subject.subscribe(...) // will eventually also get emisions from observable2

Observable<Object> observable2 = ...;
observable2.subscribe(subject);
0
votes

If I understood your problem correctly, you have several operators to pair your observables:

Now you should determine at which rate your observables produce data and how do you plan to pair the data they are producing.

For example:

  • CombineLatest - having obs1 and obs2, if obs1 produce data at a faster rate than obs2 then the data from obs1 will be paired with the latest data produced by obs2. Thus having multiple items from obs1 paired with the same item from obs2.
  • Zip - having obs1 and obs2, if obs1 produce data at a faster rate than obs2 then the data from obs1 will be paired only when obs2 will produce a value.
  • And/Then/When - is used as a convenience for combining more than two observables

NOTE: there is also a free book (for .NET - RxNET) at this LINK. Check the Pairing Sequences section in the Combining Sequences for deeper explanations and samples. The syntax is similar and the operators purpose remain across implementations.