使用 forEach 而不是订阅可观察的键盘输入事件有好处吗?

Is there a benefit to using forEach instead of subscribe with a keyboard input event observable?

当我想收听 Angular 的 FormControl.valueChanges observable 时,我正在尝试寻找确认是否应该使用 .forEach 而不是 .subscribe . FormControl API

在 Angular 的表单文档中,他们使用 .forEach 并没有真正解释原因并说您真的不需要理解它。 Document Link

我也从这个 answer 中知道 .forEach 会将一种有限持续时间的 events/incoming 值捆绑到一个承诺中。

所以我自己尝试测试 .forEach.subscribe,认为如果用户在上面输入 monkey crazy,.forEach 将在捆绑键盘输入事件方面表现得更好。

constructor(private fb: FormBuilder) {
    this.createForm();
}
private createForm() {
    this.myForm = this.fb.group({
      name: '',
    });
}

private forEach = this.myForm.get('name').valueChanges.forEach(value => {
  console.log(value, 'forEach');
});

private subscription = this.myForm.get('name').valueChanges.subscribe(value => {
  console.log(value, 'subscribe');
});

在我的测试中,在 html 输入中手动快速输入没有像我预期的那样捆绑 .forEach 值。相反,.subscribe.forEach 一次发出一个字符的值。

在这种情况下 .forEach.subscribe 有什么好处吗?如果使用 .forEach.subscribe?

虽然通常可以同时使用它们,但您需要注意 forEach 的工作方式类似于发出多个值的 Promises。

这也意味着您无法取消订阅 forEach,因此对于永远不会完成的 Observable,您很可能会造成内存泄漏(例如 valueChanges 或路由器事件)。

老实说,我不确定 valueChanges 是否完成了。我在 https://github.com/angular/angular/blob/5.0.0/packages/forms/src/model.ts#L636-L867 and they never send the complete notification. I didn't find any test that makes sure proper complete notification is sent (https://github.com/angular/angular/blob/5.0.x/packages/forms/test/form_control_spec.ts) 检查了源代码。所以我不知道他们为什么在 Angular 文档中使用 forEach。我认为他们应该改用 subscribe

我什至不明白为什么 valueChanges 无论如何都会完成。只有当你破坏了形式但你自己无法控制时。

如果你想测试任何东西,你需要知道你期望的结果是什么。不明白你写完测试想看到什么好处