Reputation: 8975
I want to perform some action with one observable say add 20 to one of its property
const mainObservable = of({id:1, count: 20});
const example = mainObservable.pipe(
map(val=> { val.count+20; return val;})
);
Then I need to check a condition of other observable and if it is true, then perform further operations like adding 40 to one of the property of first observable
Combined code:
const mainObservable = of({id:1, count: 20});
const otherObservable = of([10,20]);
const example = mainObservable.pipe(
map(val=> { val.count+20; return val;}),
switchMap(outerVal => otherObservable.pipe(map(val=>{
console.log(outerVal);
return val.length > 0;
}))),
// map(val=> {val.count+ 40, return val})
);
Here, if condition of otherObservable is true then I need to added 40 into count and at last in the subscribe I should get the actual object of first observable.
Could anybody please help me with this along with explanation? Commented code should be introduced in order to achieve the requirement so that
example observable should emit object of from first observable
Upvotes: 0
Views: 41
Reputation: 9764
Here is the updated stackblitz with your expected result.
const example = mainObservable.pipe(
map(val=> { val.count += 20; return val;}),
switchMap(outerVal => otherObservable.pipe(map(val=>{
if(val.length){
outerVal.count += 40;
}
return outerVal;
})
)),
// map(val=> {val.count+ 40, return val})
);
https://stackblitz.com/edit/rxjs-tf8r4p
Upvotes: 1
Reputation: 96891
It seems like you're looking for operators combineLatest
or withLatestFrom
depending on what logic you want. For example with withLatestFrom
you could do this like this:
const example = mainObservable.pipe(
map(val => {
val.count + 20;
return val;
}),
withLatestFrom(otherObservable),
map(([first, second]) => {
console.log(first, second);
return second.length > 0;
}),
);
Only when mainObservable
emits it takes the latest value from otherObservable
that you can use to do whatever you want.
Live demo: https://stackblitz.com/edit/rxjs-jnmehl?file=index.ts
Upvotes: 1