I have a chat application that consists of multiple components (e.g. one components holds a group list, another one contains messages, etc.), and when one component is opened another one must be closed.
So here is a service that I'm using to provide a webSocket connection:
@Injectable()
export class ChatConnectionService {
private _connection: Subject<any>;
constructor(private window: WindowAbstract) { }
public closeConnection(): void {
this.connection.complete();
}
public send(msg: ChatRequest): void {
this.connection.next(msg);
}
public messages(): Subject<any> {
return this.connection;
}
private get connection(): Subject<any> {
if (!this._connection || this._connection.closed) {
this._connection = webSocket(`https/myapp/chat`);
}
return this._connection;
}
}
And here is a usage example in some.component.ts:
private messages$: Subscription;
ngOnInit(): void {
this.messages$ = this.chatConnectionService.messages()
.subscribe(m => this.handleInboundMessage(m));
}
ngOnDestroy() {
this.messages$.unsubscribe();
}
Now the problem is that when I switch between components, once it gets unsubscribed when an old component being destroyed, a new subscription does not seem to be working, it does not send or received messages and does not produce any error as well.
But when I remove unsubscribe line it starts working, but keeps receiving messages using the old subscription as well, which is not what I really want.
So summarizing it all - I need to maintain one connection but having a possibility for multiple components to subscribe and unsubscribe as needed, is it possible to accomplish it with RxJs? Or what am I doing wrong? Any suggestion will be appreciated, thanks!