I know how to bine observables and fetch the result when all observables emit at least one value (bineLatest, 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.
I know how to bine observables and fetch the result when all observables emit at least one value (bineLatest, 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.
Share Improve this question asked Feb 11, 2022 at 13:38 enne87enne87 2,3098 gold badges36 silver badges63 bronze badges 7- Does this answer your question? RxJS bineLatest without waiting for source observables to emit? – Harun Yilmaz Commented Feb 11, 2022 at 13:42
-
Can you make sure by subscribing separately to the above
adModel
andrefreshPreview
that they are emitting? – HassanMoin Commented Feb 11, 2022 at 13:48 - You can use bineLatest. bineLatest starts emitting after one of the observable emits. forkJoin waits all to emit at least once. – Fatih Ersoy Commented Feb 11, 2022 at 14:35
- 3 merge should work, but you have to give it observables, not an array. – Mrk Sef 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. – enne87 Commented Feb 12, 2022 at 17:15
1 Answer
Reset to default 7As mentioned in the ments, 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.