简体   繁体   English

RxJS:取消订阅嵌套订阅

[英]RxJS: unsubscribe from nested subscribe

I use SockJS and StompJS and when I open my application in the browser sometimes it tries to subscribe to some topics before it even connected to the websocket.我使用 SockJS 和StompJS ,当我在浏览器中打开我的应用程序时,有时它会在连接到 websocket 之前尝试订阅一些主题。 I'd like the topic subscription wait until the app is connected to websocket.我希望主题订阅等到应用程序连接到 websocket。

export class SocksService {
...

public subscribe<T>(destination: string, callback?: (body: T) => void, headers?: object): Observable<Subscription> {
const subscription = new Subject<Subscription>();
headers = headers || {};

this.status.pipe(
  first(status => status === ConnectionStatus.CONNECTED)
).subscribe((status: ConnectionStatus) => {
  subscription.next(this.stompClient.subscribe(destination, (message: Message) => {
    if (callback) {
      callback(JSON.parse(message.body) as T);
    }
  }, headers));
});

return subscription.asObservable();
  }

...
}

That's why I implemented this code and I call it like:这就是我实现这段代码的原因,我称之为:

this.socksService.subscribe<User>('/topic/user', (user: User) => {
  console.log('user received', user);
}).subscribe(subscription => this.userSubscription = subscription);

So I subscribe to the topic only when the connection status is connected and it will be called only for the first time the client successfully connects.所以我只在连接状态为已connected时才订阅该主题,并且仅在客户端第一次成功连接时才会调用它。

I'd like to unsubscribe later from the topic, so I need the Subscription object returned by the inner subscribe and I also need the message from the inner subscribe.我想稍后取消订阅该主题,所以我需要内部订阅返回的Subscription object 并且我还需要来自内部订阅的消息。

What I implemented works good, but I think there must be a better way to do it.我实现的效果很好,但我认为必须有更好的方法来做到这一点。

(I tried rx-stomp, but it has many bugs.) (我试过 rx-stomp,但它有很多错误。)

You said you tried rx-stomp but have you tried the Angular2+ version of rx-stomp, called ng2-stompjs ?您说您尝试了 rx-stomp 但您是否尝试过 rx-stomp 的 Angular2+ 版本,称为ng2-stompjs It exposes key classes as Angular Injectable Services.它将关键类公开为 Angular 可注入服务。

See the mention of it under rx-stomp, here: https://github.com/stomp-js/ng2-stompjs#documentation在 rx-stomp 下查看它的提及,这里: https://github.com/stomp-js/ng2-stompjs#documentation

...and it's implementation (Angular 7) via a nice step-by-step, here: https://stomp-js.github.io/guide/ng2-stompjs/ng2-stomp-with-angular7.html#receiving-messages ...它的实现(Angular 7)通过一个很好的一步一步,在这里: https://stomp-js.github.io/guide/ng2-stompjs/ng2-stomp-with-angular7.html#receiving -消息

eg:例如:

this.rxStompService.watch('/topic/demo').subscribe((message: Message) => {
      this.receivedMessages.push(message.body);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM