typescript - ใน Angular นี่เป็นวิธีที่ถูกต้องในการตรวจสอบว่าการสมัครสมาชิก observable เปิดอยู่ก่อนที่จะพยายามปิดมันหรือไม่?
ใน Angular นี่เป็นวิธีที่ถูกต้องในการตรวจสอบว่าการสมัครสมาชิก observable เปิดอยู่ก่อนที่จะพยายามปิดหรือไม่? ดูเหมือนว่าจะให้ผลลัพธ์ที่ถูกต้อง นั่นคือ มันจะปิดเฉพาะการสมัครสมาชิกที่เปิดอยู่ สิ่งที่ฉันสงสัยคือ มีวิธีที่ 'ถูกต้อง' กว่านี้ในการทำใน Angular หรือไม่
import { Component, OnUpdate, OnDestroy } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { VoteService } from '../../services/vote.service';
export class Foo implements OnUpdate, OnDestroy {
private voteSubscription;
constructor(private afs: AngularFirestore,public voteService: VoteService) {}
ngOnUpdate() {
/* Lots of complicated things happen here which result in voteSubscription
being opened and closed based on external conditions including but not
limited to auth state. Bottom line is that sometimes the subscription
is active and sometimes it's not. */
if ( CONSTANTLY_CHANGING_INPUT_CONDITIONS ) {
this.voteSubscription = this.voteService.getUserVotes().subscribe();
} else {
if (this.voteSubscription) {
this.voteSubscription.unsubscribe();
}
}
}
ngOnDestroy() {
/* Avoid producing a console error if we try to close a subscription that is
already closed. */
if (this.voteSubscription) {
this.voteSubscription.unsubscribe();
}
}
}
คำตอบ #1
อ็อบเจ็กต์ Subscription ยังมีสมบัติ closed ที่สามารถใช้เพื่อตรวจสอบได้ว่าสตรีมได้ถูกยกเลิกการสมัครแล้ว (เสร็จสมบูรณ์หรือเกิดข้อผิดพลาด)
ดังนั้นถ้าคุณต้องการ คุณก็สามารถใช้มันในคำสั่ง if ได้เช่นกัน:
if (this.voteSubscription && !this.voteSubscription.closed)
อย่างไรก็ตาม สิ่งนี้ ไม่จำเป็น, RxJs ทำสิ่งนี้ภายในให้เราตามปกติ ภายในเมธอด unsubscribe คุณจะพบสิ่งที่คล้ายกับ:
if (this.closed) {
return;
}
ดังนั้นจึงสามารถเรียกยกเลิกการสมัครได้อย่างปลอดภัยโดยไม่ต้องกังวลว่าสตรีมอาจถูกปิดไปแล้ว
