【发布时间】:2021-05-09 01:28:22
【问题描述】:
我有一种情况,我有一个 observable,对于每个发射的项目,我想创建另一个 observable,但忽略该 observable 的值,而是返回第一个 observable 的结果。
例如,如果我单击一个按钮,我想跟踪另一个按钮中发生的事情,仅当第一个按钮被打开时。
我现在可以做到这一点,有点像 hack,通过获取子 observable 的输出并将其传递到带有父值的mapTo。你可以在这段代码中看到它,可以在code sandbox中玩:
import { fromEvent, from } from "rxjs";
import { mapTo, switchMap, tap, scan } from "rxjs/operators";
const buttonA = document.getElementById("a");
const buttonB = document.getElementById("b");
const textA = document.querySelector('#texta');
const textB = document.querySelector('#textb');
fromEvent(buttonA, 'click').pipe(
// this toggles active or not.
scan((active) => !active, false),
switchMap(active => {
if (active) {
const buttonBClicks$ = fromEvent(buttonB, 'click');
// here we can observe button b clicks, when button a is toggled on.
return buttonBClicks$.pipe(
// count the sum of button b clicks since button a was toggled on.
scan((count) => count+1, 0),
tap(buttonBCount => {
textB.value = `button b count ${buttonBCount}`;
}),
// ignore the value of the button b count for the final observable output.
mapTo(active)
)
} else {
textB.value = ``;
return from([active]);
}
})
).subscribe({
next: buttonActive => {
textA.value = `Button a active: ${buttonActive}`
}
});
这里有几个问题。在按钮被打开的情况下,外部 observable 只有在单击按钮后才会收到一个值。
这个mapTo 的用法看起来很老套。
有更好的方法吗?
【问题讨论】:
标签: rxjs rxjs-observables rxjs-pipeable-operators