RxJs 5 of.filter.mapTo operators -> RxJs 6

155 views Asked by At

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));
1

There are 1 answers

0
Owen Kelvin On

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'