Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use two filters?

Why do we use two filters in code below instead one?

 fromEvent<MouseEvent>(this.mapElement, "click")
    .pipe(
        filter(e => !this.props.disableEvents),
        filter(_ => !this.mouseState.moved && mouseDownInMap)
    )
    .subscribe(e => {});

Why not:

fromEvent<MouseEvent>(this.mapElement, "click")
    .pipe(filter( e => !this.props.disableEvents && !this.mouseState.moved && mouseDownInMap))
    .subscribe(e => {});

Also, why we need .pipe() if it works without pipe too?

like image 881
OPV Avatar asked Oct 12 '25 09:10

OPV


1 Answers

You can combine them into a single filter.

But for the sake of code maintenance it's often easier to read two separate filter functions, especially if they're conceptually unrelated - and to avoid horizontal scrolling.

Another reason is that the filter functions themselves may be defined elsewhere, in which case you'll have to use separate filter calls anyway:

e.g.

function whenEventsAreEnabled( e ) {
    return !this.props.disableEvents;
}

function whenMouseIsInMap( e ) {
    !this.mouseState.moved && mouseDownInMap
}

fromEvent<MouseEvent>(this.mapElement, "click")
    .pipe(
        filter( whenEventsAreEnabled ),
        filter( whenMouseIsInMap )
    )
    .subscribe(e => {});

Also, why we need .pipe() if it works without pipe too?

You do need pipe. You can only get-away without using pipe if you're using RxJS in backwards compatibility mode. Modern RxJS always requires pipe() to create a pipeline for the observable's emitted values/objects.

like image 182
Dai Avatar answered Oct 15 '25 01:10

Dai