0

I have two streams :

const sourceOne = of(1, 2, 3);
const sourceTwo = of(4, 5, 6);
const example = sourceOne.pipe(concat(sourceTwo)); //123456

As you see , I've concatenated them unconditionally.

But it turns out that I need to concat them only if the first item from sourceOne is "even". (%2==0)

Question:

How can I concat sourceTwo to sourceOne by adding conditions regarding the first stream ?

I know I can create an external method which will be piped , but I don't think it's the RXJS way of doing it.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

2

If sourceOne is a cold Observables, as in your example, then you can try something along these lines

const example = sourceOne.pipe(
  take(1),
  switchMap(d => d % 2 === 0 ? sourceOne.pipe(concat(sourceTwo)) : empty()),
)

If instead sourceOne is a hot Observable, you can try something like this

const sourceOneHot = of(1, 2, 3).pipe(share());
const exampleHot = sourceOneHot.pipe(
  take(1),
  switchMap(d => d % 2 === 0 ? concat(of(d), sourceOneHot, sourceTwo) : empty()),
);

To create a hot source Observable you can use

Picci
  • 16,775
  • 13
  • 70
  • 113
  • 1
    I think you mean `switchMap(d => d % 2 ? sourceOne : sourceOne.pipe(concat(sourceTwo)))` or `switchMap(d => sourceOne.pipe(concat(d % 2 ?empty() : sourceTwo)))`. Your version shows either concatenated arrays (for even d) or nothing (for odd d) – barbsan Oct 03 '18 at 09:37
  • I understand this is the requirement: nothing is emitted if the first element of `sourceOne` is null. – Picci Oct 03 '18 at 09:44
  • ^ Right. but if the first stream has a first "odd" value , emit only it. , otherwise , emit also the second stream – Royi Namir Oct 03 '18 at 10:10