Last active
June 29, 2019 12:56
-
-
Save Gbuomprisco/22f82d4728a4661001dea2c6aa6d6087 to your computer and use it in GitHub Desktop.
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
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