2

I have two IObservable<T>, and want to create a IObservable<Unit> (or some sort of ISingle<Unit>, if such a thing exists) that emits a completion signal when both complete, and nothing else. What's the idiomatic way to do this in Rx.NET?

I'm used to Reactor Core, in which case I'd use flux1.then().and(flux2.then()). But I don't believe Rx.NET offers the then and and operators.

jack
  • 147
  • 1
  • 7
  • What is the desirable behavior if one of the sequences fail before the other one has completed? – Theodor Zoulias Oct 29 '21 at 16:59
  • Ideally an error should be throw as soon as one fails. – jack Oct 29 '21 at 17:00
  • 1
    In this case you may want to check out this question: [How to merge two observables with early completion](https://stackoverflow.com/questions/59261017/how-to-merge-two-observables-with-early-completion) – Theodor Zoulias Oct 29 '21 at 17:07
  • Thank you @TheodorZoulias. – jack Oct 29 '21 at 17:08
  • 1
    jackdry actually the built-in `Merge` operator has exactly the behavior that you want. As soon as one of the sequences fails, the merged sequence fails immediately too. And the other sequence, if it hasn't completed yet, is unsubscribed. – Theodor Zoulias Oct 29 '21 at 17:33

1 Answers1

1

Assuming that both sequences are of the same type, you could use the Merge operator. It might be beneficial to throw the IgnoreElements in the mix, in order to reduce the synchronization stress associated with merging sequences that may contain huge number of elements.

IObservable<Unit> completion = sequence1.IgnoreElements()
    .Merge(sequence2.IgnoreElements())
    .Select(_ => Unit.Default);

If the sequences are of different type, you could project each one of them to an IObservable<Unit> before merging, or use the CombineLatest instead of the Merge. Lots of options.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • 1
    Thank you! Why do we need `LastOrDefaultAsync()` though? – jack Oct 29 '21 at 17:01
  • 1
    @jackdry good question! We don't need it, so I'll remove it from the answer. The `LastOrDefaultAsync` is needed if you want to `Wait` or `await` the sequence, because awaiting empty sequences results to an exception. – Theodor Zoulias Oct 29 '21 at 17:04