Reputation: 2129
I've inherited some old RxJs 5
code that smells awkward:
myFunc = (tag: TagModel): Observable<TagModel> => {
try {
const foundTag = this.mappedTags.find((x) => {
return x.name === tag;
});
const isAllowedToAdd = foundTag ? false : true;
return Observable
.of(tag)
.filter(() => isAllowedToAdd)
.mapTo(tag);
} catch (err) {
console.log("err: ", err);
}
}
Is the purpose of that code to create an Observable with either a value of tag if it's found, otherwise empty? It looks so convoluted (plus some other choice words which I can't share here).
RxJs
introduced breaking changes where of
and mapTo
are no longer chainable. Would this be the correct way to refactor?
return of(tag)
.filter(() => isAllowedToAdd)
.pipe(mapTo(tag));
Upvotes: 1
Views: 163
Reputation: 15083
Below Should work
myFunc = (tag: TagModel): Observable<TagModel> => {
try {
const foundTag = this.mappedTags.find((x) => x.name === tag);
const isAllowedToAdd = !foundTag;
return of(tag).pipe(
filter(() => isAllowedToAdd)
)
} catch (err) {
console.log("err: ", err);
}
}
Remember to include import { of } from 'rxjs'
and import { filter } from 'rxjs/operators'
Upvotes: 1