2

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.

7
  • Does this answer your question? RxJS combineLatest without waiting for source observables to emit? Commented Feb 11, 2022 at 13:42
  • Can you make sure by subscribing separately to the above adModel and refreshPreview that they are emitting? Commented Feb 11, 2022 at 13:48
  • You can use combineLatest. combineLatest starts emitting after one of the observable emits. forkJoin waits all to emit at least once. Commented Feb 11, 2022 at 14:35
  • 3
    merge should work, but you have to give it observables, not an array. Commented Feb 11, 2022 at 14:37
  • Sorry but none of your advices did the trick. I have to use "startsWith" to initialize the observables. Otherwise, it does not work. Commented Feb 12, 2022 at 17:15

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'll re-check it. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.