Skip to content

Instantly share code, notes, and snippets.

@evandocarmo
Created August 22, 2017 11:08
Show Gist options
  • Save evandocarmo/f8e5c5a9ed49fa147137b7f05ae0e169 to your computer and use it in GitHub Desktop.
Save evandocarmo/f8e5c5a9ed49fa147137b7f05ae0e169 to your computer and use it in GitHub Desktop.
/* 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 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