RxJs Observable: Execute function if empty/filtered

Viewed 15996

I've got an Observable that listens to some user input from a text box. If the observed string's length is >=3 (filter), it executes some HTTP call (switchMap).

Now I'd like to detect somehow if the user input has been filtered. Reason:

  • If the HTTP call has been done, it should show the results.

  • If the user input got filtered (== is invalid), it should clear the results.

Here's the code I'd like to have (see: ifFiltered):

this.userInput.valueChanges
    .filter(val => val && val.length >= 3)
    .ifFiltered(() => this.results = [])
    .switchMap(val => getDataViaHTTP())
    .subscribe(val => this.results = val);

I know, I could place that logic within the filter function for this simple example. But what if I have 10 different filters?

Did I miss any method that satisfies my needs?

Thanks in advance!

5 Answers

May be it's late, but wanted to post for the members still seeking a more cleaner approach to validate IF EMPTY inside .map:

of(fooBar).pipe(
      map(
        (val) =>
          ({
            ...val,
            Foo: (val.Bar
              ? val.Foo.map((e) => ({
                  title: e.Title,
                  link: e.Link,
                }))
              : []) as fooModal[],
          }));

This code returns a empty array if val.bar is missing, but it's just an example you can use any validation & expression instead.

Related