Reputation: 39394
I am checking a condition and getting an Observable<boolean>
:
let result = this.service.getCity().pipe(
map((city: string) => city && city.toLowerCase() === ???)
);
I need to check if the city
equals:
this.authenticationService.getCity():
This method also returns and Observable<boolean>
.
How can I combine the two observables and use both values in a condition?
I need to return an Observable at the end.
Upvotes: 2
Views: 2478
Reputation: 4267
Alternative to forkjoin
If observable completion
is not the trigger to compare both observables, you can use switchMap
const { from, of } = rxjs;
const { map, switchMap, tap, take } = rxjs.operators;
const serviceCity$ = () => from(['Berlin', 'London', 'Paris']);
const authentificationCity$ = () => of('london');
const result$ = serviceCity$().pipe(
map(city => city && city.toLowerCase()),
switchMap(city => authentificationCity$().pipe(
map(authCity => city === authCity),
take(1),
))
);
result$.subscribe(v => console.log('authentification city equals london: ', v));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
Info
serviceCity$
and authentificationCity$
equal your service.getCity()
and this.authenticationService.getCity()
string
and you want to compare both strings
. If you want to compare two pre-mapped
values then explain me and I will update the code.result$
will fire whenever serviceCity$
emits followed by an emit of authentificationCity$
take(1)
avoids the result$
being triggered by authentificationCity$
instead of serviceCity$
Upvotes: 2
Reputation: 5470
Assuming this.service.getCity()
and this.authenticationService.getCity()
returns singular object/string based on how you named it.
You can use forkJoin
operator. Here's an example
const source1 = of("CityName");
const source2 = of("CityName");
forkJoin({
source1,
source2
}).pipe(
map((x: {source1, source2}) => x.source1 === x.source2)
).subscribe(result => console.log(result));
StackBlitz: https://stackblitz.com/edit/rxjs-luncbd
Upvotes: 1