在
this.route.params
被销毁并且this.sub
被取消订阅后,"interval run"
仍然在记录日志。这与我的直觉相反,即在取消订阅后,所有操作都应该停止。这里发生了什么,以及处理它的最佳方法是什么?我应该添加一个takeUntil,还是应该使用concatMap之外的其他东西?(我正在轮询新照片) constructor(private authService:AuthService,
private route:ActivatedRoute,
private router:Router,
private photosApi:PhotosApi) {
}
ngOnInit() {
this.sub = this.route.params
.switchMap(()=>{
console.log('switchmap Ruun')
return Observable.interval(2000).startWith(0).concatMap(()=>{
console.log('interval run')
return this.photosApi.apiPhotosGet(this.authService.getAuth(), 0, 40)
})
})
.subscribe((data:PagedResultPatientPhotoModel) => {
this.processPhotos(data)
}).add(()=>console.log('unsubscribe happened'))
编辑:我尝试重新编写以使其更清晰,使用concatMap仅进行一次调用,但我不确定为什么它在第一次调用后停止工作:
this.intervalSub = Observable.interval(3000).startWith(0).concatMap(()=>{
console.log('getting photos interval', this.route.params)
return this.route.params.switchMap(()=>{
console.log('getting photos')
return this.photosApi.apiPhotosGet(this.authService.getAuth(), 0, 40)
})
}).subscribe((data:PagedResultPatientPhotoModel) => {
this.processPhotos(data)
}).add(()=>console.log('unsubscribe happened'))
如果api调用可以在3000毫秒内运行完,那么以下使用switchMap的内容是有效的,否则它们会相互取消:
this.intervalSub = Observable.interval(3000).startWith(0).switchMap(()=>{
console.log('getting photos interval', this.route.params)
return this.route.params.switchMap(()=>{
console.log('getting photos')
return this.photosApi.apiPhotosGet(this.authService.getAuth(), 0, 40)
})
}).subscribe((data:PagedResultPatientPhotoModel) => {
this.processPhotos(data)
}).add(()=>console.log('unsubscribe happened'))
我很好奇为什么switchMap(和mergeMap)每次都可以工作,但concatMap只能工作一次,看起来像是RXJS中的一个错误。
我决定使用mergeMap,因为我觉得它不太可能出现请求返回顺序错误的情况,即使出现这种情况,几秒钟后也会自行纠正。