Last active
June 17, 2019 04:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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