enne87
enne87

Reputation: 2309

RxJS - Combine multiple observables and emit any value

I know how to combine observables and fetch the result when all observables emit at least one value (combineLatest, forkJoin, etc.).

But how can I emit a value when one of many observables emits a value?

For example:

const adModelChangedObs$ = this.editAdService.adModelChanged; // Angular subject one
const refreshPreviewClickedObs$ = this.editAdService.refreshPreviewClick // Angular subject two

merge([adModelChangedObs$, refrshPreviewClickedObs$]).subscribe(() => {
     console.log('One of the two observables emitted a value');
});

The subscribe handler is not being executed, although I tried it with many RxJS operators for far.

Upvotes: 2

Views: 8868

Answers (1)

Amer
Amer

Reputation: 6716

As mentioned in the comments, the merge function should help in your case, however, you have to pass the observables as args, not as an array.

You can try it like the following:

// import { merge } from 'rxjs';

const adModelChangedObs$ = this.editAdService.adModelChanged; // Angular subject one
const refreshPreviewClickedObs$ = this.editAdService.refreshPreviewClick; // Angular subject two

merge(adModelChangedObs$, refrshPreviewClickedObs$).subscribe(() => {
  console.log('One of the two observables emitted a value');
});

However, if that's not working, then you need to make sure that your editAdService observables emit the value correctly.

Upvotes: 7

Related Questions