2 回答
TA贡献1942条经验 获得超3个赞
以下有您想要的输出。我不确定它是否符合您的标准。你内心的可观察是否有理由必须成为行为主体?如果只是给它一个初始值,那么startWith操作员会做得更干净。
const outer = new Subject();
const inner = new Subject();
const http = of("");
const mapped = outer.pipe(
switchMap(outerVal =>
inner.pipe(
startWith(0),
map(innerVal => ({ innerVal, outerVal }))
)
),
switchMap(({ innerVal, outerVal }) =>
http.pipe(
tap(() => console.log("http: ", outerVal, innerVal))
)
)
);
mapped.subscribe(console.log); // ""
你的 stackblitz 内存泄漏
您正在创建长期存在的多播流,但从未完成它们。你可以尝试:
tap(() => {
inner2.complete();
inner2 = new BehaviorSubject(0);
}),
SwitchMap 将取消订阅,但多播流在取消订阅时不会完成(取决于其refcount工作原理)。
TA贡献1859条经验 获得超6个赞
考虑下面的方法,我将两个Observable流和过滤器组合起来只发出 1 个值。然后我们可以使用新的流与http请求合并
const http = of("");
const triggerSubject$ = new BehaviorSubject({ inner: 0, outer: null });
const trigger = triggerSubject$.pipe(
filter(({ inner, outer }) => inner && outer)
);
const triggerInner = val => {
console.log("Inner", val);
return triggerSubject$.next({
inner: val,
outer: triggerSubject$.value.outer
});
};
const triggerOuter = val => {
console.log("Outer", val);
return triggerSubject$.next({ inner: 0, outer: val });
};
const mapped = trigger.pipe(
switchMap(({ inner: innerVal, outer: outerVal }) =>
http.pipe(tap(() => console.log("http: ", outerVal, innerVal)))
)
);
mapped.subscribe(result => {
console.log(result);
});
triggerOuter("first");
triggerInner(1);
triggerInner(2);
triggerOuter("second");
triggerInner(3);
添加回答
举报