Skip to content

Instantly share code, notes, and snippets.

@Gbuomprisco
Last active June 29, 2019 12:56
Show Gist options
  • Save Gbuomprisco/22f82d4728a4661001dea2c6aa6d6087 to your computer and use it in GitHub Desktop.
Save Gbuomprisco/22f82d4728a4661001dea2c6aa6d6087 to your computer and use it in GitHub Desktop.
const WEB_SOCKET_ENDPOINT = 'wss://ws.coincap.io/prices/';
@Injectable()
export class PriceApiService implements PriceApi {
private webSocket: WebSocket;
public getPrice(currency: string): Observable<string> {
return this.connectToPriceStream(currency);
}
public unsubscribe() {
this.webSocket.close();
}
private connectToPriceStream(asset: string): Observable<string> {
this.createConnection(asset);
return new Observable(observer => {
const webSocket = this.webSocket;
webSocket.onmessage = (msg: MessageEvent) => {
const data = JSON.parse(msg.data);
observer.next(data[asset]);
};
return {
unsubscribe(): void {
webSocket.close();
}
};
});
}
private createConnection(asset: string) {
if (this.webSocket) {
this.webSocket.close();
}
this.webSocket = new WebSocket(
WEB_SOCKET_ENDPOINT + `?assets=${asset}`
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment