取消订阅可观察对象后如何重新订阅

时间:2020-06-27 20:19:45

标签: angular typescript rxjs

我创建了一个socketService,在其中我不断获取数据更新,并且在我的组件上订阅了我的getUpdates Observable。

我必须取消订阅stop操作,然后再次订阅start操作按钮。

退订在stop动作上效果很好,但是之后,它不再在start动作按钮上再次订阅。

这是我的socketService:

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);
  });

任何帮助将不胜感激。 谢谢

1 个答案:

答案 0 :(得分:0)

您可以根据status.action的值使用相同的主题sub进行订阅/取消订阅。 sub.complete()完成了可观察流,因此可观察对象将不再发射任何值。

 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;
}