首页 > 解决方案 > 我怎样才能防止CombineLatest第一次触发

问题描述

我有一个包含一堆字段的表单(使用reactiveForm)。当字段 A 或 B 中的值发生变化时,我想执行 doStuffWithAnB。

所以 combineLatest 似乎是我需要的。

combineLatest(A.valueChanges,B.valueChanges).subscribe(doStuffWithAnB)

现在如果用户进入表单,并且只触摸 B(或 A),我想执行我的功能,> 这里是 startWith

combineLatest(A.valueChanges.pipe(startWith(someDefaultValue),B.valueChanges.pipe(startWith(someOtherDefaultValue)).subscribe(doStuffWithAnB)

但是现在 doStuffWithAnB 从一开始就被触发,因为我的 2 个流有一个 startWith,但是我不想执行 doStuffWithAnB,直到其中一个字段被修改

我怎样才能以干净的方式实现这一目标?

标签: angularrxjsangular-reactive-formscombinelatest

解决方案


为什么不去merge取而代之,它将采取任何一个结果!我们也不需要startsWith,因为它最初不应该执行!

从:

 combineLatest(A.valueChanges.pipe(startWith(someDefaultValue),B.valueChanges.pipe(startWith(someOtherDefaultValue)).subscribe(doStuffWithAnB)

至:

merge(A.valueChanges,B.valueChanges).subscribe(doStuffWithAnB)

推荐阅读