Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJs Observable: Execute function if empty/filtered

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!

like image 393
Benjamin M Avatar asked Mar 12 '16 09:03

Benjamin M


People also ask

How do you know if an Observable object is empty?

The RxJS isEmpty() operator returns an observable with a Boolean value indicating whether the observable was empty or not. It returns an output as true if the source observable is empty; otherwise, false.

What is an empty Observable?

A simple Observable that emits no items to the Observer and immediately emits a complete notification.

How does RxJS filter work?

RxJS filter() operator is a filtering operator used to filter items emitted by the source observable according to the predicate function. It only emits those values that satisfy a specified predicate. The RxJS filter() operator is like the well-known Array Array . prototype.

What does complete do in Observable?

Complete value: With the complete value, the observer sends no value. This usually signals that the subscriptions for that particular Observable is complete. If the complete value is sent, nothing else can be delivered to the Observable.


1 Answers

Either use partition like here RxJS modeling if else control structures with Observables operators

Or instead of filter use map and pipe the object if the former filter condition is true or null otherwise. so you can catch the null where ever you want in your chain with a filter.

Last option call some function in the else part of the filter function

like image 107
Markus Avatar answered Sep 19 '22 22:09

Markus