【发布时间】:2026-01-20 20:00:01
【问题描述】:
这里是要求:
当点击开始按钮时,每 100 毫秒发出 x 次事件,每次发出对应一个 UI 更新。 x次emit完成后,会触发最后一次UI更新,看起来很简单吧?
这是我的代码:
const start$ = fromEvent(document.getElementById('start'), 'click')
const intervel$ = interval(100)
.pipe(
take(x),
share()
)
var startLight$ = start$
.pipe(
switchMap(() => {
intervel$
.pipe(last())
.subscribe(() => {
// Update UI
})
return intervel$
}),
share()
)
startLight$
.subscribe(function (e) {
//Update UI
})
显然,在switchMap 内订阅是反模式,所以我尝试重构我的代码:
const startInterval$ = start$
.pipe(
switchMapTo(intervel$),
)
startInterval$.pipe(last())
.subscribe(() => {
//NEVER Receive value
})
const startLight$ = startInterval$.pipe(share())
问题是intervel$流是在switchMap里面产生的,外面不能访问,只能访问产生intervel$的流,即start$永远不会完成!
是否有更聪明的方法来处理此类问题,或者这是 rxjs 的固有限制?
【问题讨论】:
标签: rxjs observable