无法从rxjs 5.0中取消可观测
我有这个功能:无法从rxjs 5.0中取消可观测,rxjs,Rxjs,我有这个功能: uploadFiles(files: FileToUpload[]) { return Observable.create(async (observable) => { const aborters: Aborter[] = []; for (const fileToUpload of files) { let uploadResponse: UploadResponse; const aborter
uploadFiles(files: FileToUpload[]) {
return Observable.create(async (observable) => {
const aborters: Aborter[] = [];
for (const fileToUpload of files) {
let uploadResponse: UploadResponse;
const aborter = Aborter.none;
aborters.push(aborter);
try {
uploadResponse = await this.upload(file)
} catch (err) {
}
}
return () => {
console.log('coooo');
this.files$.next([]);
for (const aborter of aborters) {
if (!aborter.aborted) {
aborter.abort();
}
}
};
});
}
我希望当用户从apge导航awwy时,如果发生下载,可以取消该观察,因此我返回一个在取消订阅调用时调用的函数
然后我这样订阅:
this.uploadSubscription = this.uploadService.uploadFiles(this.control.value).subscribe(
() => console.log('progress'),
(e) => {
console.log(`errored with ${e}`);
this.uploadSubscription.unsubscribe();
},
() => {
console.log('completed');
this.uploadSubscription.unsubscribe();
}
);
ngOnDestroy() {
if (this.uploadSubscription) {
this.uploadSubscription.unsubscribe();
}
}
我有一个ngondestory
像这样:
this.uploadSubscription = this.uploadService.uploadFiles(this.control.value).subscribe(
() => console.log('progress'),
(e) => {
console.log(`errored with ${e}`);
this.uploadSubscription.unsubscribe();
},
() => {
console.log('completed');
this.uploadSubscription.unsubscribe();
}
);
ngOnDestroy() {
if (this.uploadSubscription) {
this.uploadSubscription.unsubscribe();
}
}
但是,即使调用了unsubscribe方法,从
Observable.create
返回的回调也不会被调用。我认为问题在于,从Observable.create
回调返回的实际上是承诺,而不是拆卸方法
您使用async
关键字标记了回调,因此它返回一个承诺,因此当您稍后调用return()=>{}
时,实际上返回的是Promise void>
,因此它从未被调用。即使在您呼叫取消订阅
时也不行
你必须根据你想做的事情重新组织链,使其不可订阅,但似乎你甚至不需要使用
wait
,因为你从不向观察者推送任何通知
我想你可以使用takeUntil
。我需要调用回调函数,它不会被调用,直到使用destry$
时才会被调用,绝对是个傻瓜。当然,async会返回一个承诺。非常感谢。