为什么我们使用两个过滤器?

Why do we use two filters?

为什么我们在下面的代码中使用两个而不是一个过滤器?

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

为什么不呢:

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

此外,如果没有管道也能工作,为什么我们需要 .pipe()

可以将它们组合成一个filter

但为了代码维护,通常更容易阅读两个单独的过滤器函数,尤其是当它们在概念上不相关时 - 并避免水平滚动。

另一个原因是过滤器函数本身可能在别处定义,在这种情况下,无论如何您都必须使用单独的 filter 调用:

例如

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?

需要pipe。如果你在 backwards compatibility mode. Modern RxJS always requires pipe() to create a pipeline for the observable's emitted values/objects.

中使用 RxJS,你只能在不使用 pipe 的情况下逃脱

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

您不需要它,但是当多个操作员要执行操作时它会提高可读性。来自 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(),
)