You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用combineLatest/zip仅响应第二个Observable发射,忽略第一个变更

解决方案

你当前用zip操作符的问题在于,只要mapObjects$或currentMapObjectsIndex$任意一个发射新值,currentMapObject$就会被触发,这不符合你只响应索引变化的需求。

要实现仅当currentMapObjectsIndex$发射数据时才更新currentMapObject$,同时在触发时获取mapObjects$的当前最新值,应该用withLatestFrom操作符:

this.currentMapObject$ = this.currentMapObjectsIndex$.pipe(
  withLatestFrom(this.mapObjects$),
  map(([index, mapObjects]) => mapObjects[index])
);

原理说明

  • withLatestFrom会以**源Observable(这里是currentMapObjectsIndex$)**的发射为触发条件,只有当源Observable发射新值时,才会去获取mapObjects$的最新值,组合后传递给后续操作。
  • 当mapObjects$单独发生变更时,不会触发currentMapObject$的发射,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Felix Olszewski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:06:29