我正在开发一些代码,其中只要一个复选框为真,一些输入将计算一些值并修改其他输入,所以我来到了这样的解决方案
// boolean observable
this.toggleObservable.subscribe((value)=>{
if (value) {
this.dataService.calculateValuesObservable.subscribe(...logic that changes the values reactively)
}
})
问题是当我设置开关关闭时,我无法取消订阅calculateValuesObservable
有什么建议吗?
您可以使用switchMap取消订阅以前的订阅,并且当复选框禁用时永远不要跳过
import { NEVER } from 'rxjs';
import { switchMap } from 'rxjs/operators';
this.toggleObservable.pipe(
switchMap((isChecked) => isChecked
? this.dataService.calculateValuesObservable
: NEVER
),
).subscribe((value) => {
console.log(value);
})
我会这样做:
this.dataService.calculateValuesObservable.pipe(
withLatestFrom(this.toggleObservable), // get the value of toggle
filter(([toggle, value]) => !!toggle), // only continue with pipe if toggle is true
map(([toggle, value]) => value) // transform the result
).subscribe(value => {
// logic that changes the values reactively
})
订阅calculateValuesObservable
并将其与toggleObservable
的最新值合并。然后用toggle
的值替换filter
。