Created
August 22, 2017 11:08
-
-
Save evandocarmo/3203dd9e6e884001754c8e8326b1f102 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
/* The goal of this gist is to try and clarify the following code... */ | |
import { | |
Injectable | |
} from '@angular/core'; | |
import { | |
Observable | |
} from 'rxjs/Observable'; | |
import { | |
Subject | |
} from 'rxjs/Subject'; | |
import { | |
Observer | |
} from "rxjs/Observer"; | |
@Injectable() | |
export class WebsocketService { | |
/* A subject is a class that serves both as observer and observable, pushing and pulling data */ | |
private subject: Subject < MessageEvent > ; | |
/* This returns the property subject if it exists. If it doesn't, it creates it */ | |
public connect(url: string): Subject < MessageEvent > { | |
if(!this.subject) | |
this.subject = this.create(url); | |
return this.subject; | |
} | |
/* Method called by the connect method if the Subject does not yet exist, creating it */ | |
private create(url: string): Subject < MessageEvent > { | |
let socket = new WebSocket(url); | |
/* An observable can be subscribed to. The argument to the create method is function defining what data | |
it'll push forward to observers subscribed to it*/ | |
let observable = Observable.create((observer: Observer < MessageEvent > ) => { | |
socket.onmessage = observer.next.bind(observer); //bind messages received through the socket to the observer | |
socket.onerror = observer.error.bind(observer); | |
socket.onclose = observer.complete.bind(observer); | |
return socket.close.bind(observer); | |
}); | |
/* I understand this is the observer part that'll compose the Subject.However, I do not understand what's going on.*/ | |
let outObserver = { | |
next: (data: Object) => { | |
if(socket.readyState === WebSocket.OPEN) | |
socket.send(JSON.stringify(data)); | |
} | |
} | |
return Subject.create(outObserver, observable); | |
} | |
constructor() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment