如何使用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
相关产品推荐
相关产品推荐

