POV
POV

Reputation: 12015

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?

Upvotes: 4

Views: 123

Answers (2)

fjplaurr
fjplaurr

Reputation: 1950

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

You don't need it but it improves readibility when several operators are going to act. From docs:

Pipeable operators are functions, so they could be used like ordinary functions: op()(obs) — but in practice, there tend to be many of them convolved together, and quickly become unreadable: op4()(op3()(op2()(op1()(obs)))). For that reason, Observables have a method called .pipe() that accomplishes the same thing while being much easier to read:

obs.pipe(
  op1(),
  op2(),
  op3(),
  op3(),
)

Upvotes: 1

Dai
Dai

Reputation: 155513

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.

Upvotes: 10

Related Questions