簡體   English   中英

取消訂閱 Observable 后如何重新訂閱

[英]how to re-subscribe after unsubscribing an Observable

我創建了一個 socketService,我在其中不斷獲取數據更新,並且在我的組件上我訂閱了我的 getUpdates Observable。

我必須取消訂閱stop操作並再次訂閱start操作按鈕。

取消訂閱在stop操作時效果很好,但之后它不會在start操作按鈕上再次訂閱。

這是我的套接字服務:

getUpdates() {
    let sub = new Subject();
    let subObservable = from(kioskSub)

   this.socket.on('receive', (updates: any) => {
     sub.next(updates);
   });
   this.socket.on(`master_receive`, (status: any) => {
        sub.next(JSON.stringify(status));
        if (status.action && status.action === 'stop') {
            sub.complete();
        } // i want to stop subscription here
        if (status.action && status.action === 'start') {
            sub.next(JSON.stringify(status));
        } // and start here
    });
   return subObservable;
}

Component: // 我在哪里訂閱 getUpdates

 this.subscription = this.socketService.getUpdates().subscribe((latestdata: string) => {
       this.status = JSON.parse(latestStatus);
  });

任何幫助,將不勝感激。 謝謝

您可以根據status.action的值使用相同的Subject sub來訂閱/取消訂閱。 sub.complete()完成了 observable stream ,因此 observable 不會發出更多值。

 getUpdates() {
    let sub = new Subject();
    let subObservable = from(kioskSub)

   this.socket.on('receive', (updates: any) => {
     sub.next(updates);
   });
   this.socket.on(`master_receive`, (status: any) => {
        sub.next(JSON.stringify(status));
        if (status.action && status.action === 'stop') {
            sub.unsubscribe();
        } // i want to stop subscription here
        if (status.action && status.action === 'start') {
            sub.next(JSON.stringify(status));
        } // and start here
    });
   return sub;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM