问题描述
我创建了一个socketService,在其中我不断获取数据更新,并且在我的组件上订阅了我的getUpdates Observable.
I have created a socketService where i am continously getting data updates and on my component i am subscribing my getUpdates Observable.
我必须取消订阅 stop
操作,然后再次订阅 start
操作按钮.
I have to unsubscribe on stop
action and subscribe again on start
action button.
退订在 stop
动作上效果很好,但是之后,它不再在 start
动作按钮上再次订阅.
Unsubscribe works well on stop
action but after that it doesnt subscribe again on start
action button.
这是我的socketService:
Here is my 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的地方
Component: // where i am subscribing getUpdates
this.subscription = this.socketService.getUpdates().subscribe((latestdata: string) => {
this.status = JSON.parse(latestStatus);
});
任何帮助将不胜感激.谢谢
Any help would be appreciated.Thanks
推荐答案
您可以根据status.action的值使用相同的Subject sub
进行订阅/取消订阅. sub.complete()
完成可观察的流,因此可观察的对象将不再发射任何值.
You can use the same Subject sub
to subscribe/unsubscribe according to the value of status.action. sub.complete()
completes the observable stream and so no more values will be emitted by the 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;
}
这篇关于取消订阅可观察对象后如何重新订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!