Skip to content

Instantly share code, notes, and snippets.

@VlnRbn
Last active June 17, 2019 04:51
Show Gist options
  • Save VlnRbn/601c52721f4cdaff703d8e1f00f5c63c to your computer and use it in GitHub Desktop.
Save VlnRbn/601c52721f4cdaff703d8e1f00f5c63c to your computer and use it in GitHub Desktop.
Snippet for integrating websockets using rxjs. Below code is using an integration example for angular
import { Injectable } from '@angular/core';
import {WebSocketSubject, webSocket} from 'rxjs/webSocket'
@Injectable({providedIn: 'root'})
export class WebsocketBaseService {
private serverMessages : Array<any>
private socket$: WebSocketSubject<any>;
private readonly socketURL = "url"
constructor() {
this.socket$ = webSocket(this.socketURL);
this.connect();
}
connect(){
this.socket$
.subscribe(
(message) => {
this.serverMessages.push(message);
},
err =>{
// "Could not connect to socekts server",
} ,
() => console.log('Completed!')
);
}
/**
* @description multiplex multiple messages over the same channel
* @param type unique message indentifier, may be api name
* @param message information to send to backend is an JSON Object
* @returns an Observable, subscribe to catch server message
* @reference https://rxjs-dev.firebaseapp.com/api/webSocket/webSocket
*/
multiplexSend( type : string, message: any ){
return this.socket$.multiplex(
() => message,
() => JSON.stringify({"unsubscribe" : type}),
message => message.Operation == type
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment