RxJS5 WebSocketSubject and socket.io - websocket

Can someone please guide me in the right direction for using socket.io with RxJS?
I've been experimenting with my own implementation, but was wondering if there is a preferred standard.
I've seen RxJS5's WebSocketSubject, is there something similar that works with socket.io?
Thanks in advance

What I do in my app is wrap an event form socket io using the fromEventPattern. This way, you get an observable with every event that is being passed to the socket. There is not really a need to have a separate library do this for you I guess.
Rx.Observable.fromEventPattern(
function add (h) {
socket.on('whatever event you are throwing',h);
}
);

Related

Socket.IO acknowledgement vs event emitting

I'm trying to build application (to be more accurate a library for my personal projects) which will be based on room management (lobby, matchmaking, rooms, etc).
I managed to do it with socket.io.
Now, my question is, I don't know what kind of design pattern should I use.
I noticed that socket.io has ack callbacks, which surprised me and think it's good, but I'm not sure what's the difference between sending back ack with parameters or emitting an event with parameters.
So, question is, what's the pros and cons using acks over emitting an event and vice-versa?
Let's say, what's the pros and cons using following codes:
assuming handler callback is fn(err, res);
acknowledgement style:
socket.on('join', function (data, ack) {
// do the joining stuff here.
return ack(null, { response: 'goes_here' });
});
versus
event emitting style:
socket.on('join', function (data, ack) {
// do the joining stuff here.
io.to(client_sid).emit('join_response', null, { response: 'goes_here' });
});
As you noted, there is not a real difference if you only think about the ping-pong thing. I would the notable changes is that it allows you to validate a specific event has been acknowledged (although you could argue that you can also do that with a _response event by passing an event id), and provides a more convenient way to handle responses, by using a simple callback style notation: the first example looks way cleaner and simple.
Besides, it allows you to avoid creating two event keys for just one type of event which is kinda repeating. Acknowledgement has been made for this purpose, so there is no real reason not to use it in favor or creating another event.

Node.js + Angular 2 RxJS Observabes & Change Detection - Best way to utilize Ajax Service with REST API?

I am very new to Angular 2 and do not know much about RxJS or the nature of observables. I am trying to achieve a certain functionality however, and am just looking for a guide to the right information I should be learning to achieve this and a more thorough knowledge.
I am working on a basic web application which is more of a test than anything, where several of my Angular 2 routed views will need to be asynchronously getting data from a REST API endpoint I built in Node.js.
Here is what I am trying to achieve:
When I route (with Angular) to site.com/messages there will be a view, whose component will be utilizing a service which is pulled in through a parent component's providers array. I need this service to constantly get data from the API endpoint site.com/api/messages.
It seems to me that the most intuitive way to do this would be to have the the component that needs the data setup an http.get() on setInterval() when the component is initialized (ngOnInit life cycle hook). This will repeatedly poll the endpoint I need, so that it gets the data for the view which can use a structural directive to iterate through it or something like that.
Issue with this is I feel that it is a very primitive way to handle getting data. I would like to be using the newest and most effective and efficient way to do this. Unfortunately I am very new to Angular 2 and am not very familiar with some of the technologies and practices behind it. I have heard of and seen RxJS observables, Angular change detection, RxJS observable streams, and am wondering what the best way to learning these and what exactly will they buy me as far as asynchronous data fetching with an Angular 2 service. Any information as to how to utilize these technologies and how they all fit together would be great. Thanks
You should use the interval method of the Observable class. For example:
constructor() {
initializePolling().subscribe(
(data) => {
this.dataToDisplay = data;
}
);
}
initializePolling() {
return Observable
.interval(60000)
.flatMap(() => this.getNewMessages());
}
You can then use dataToDisplay in the component template directly.
You can also leverage the async pipe to display an observable:
constructor() {
this.dataToDisplay = initializePolling();
}
And in the template for example:
<div *ngFor="d of dataToDisplay | async">{{d.someProperty}}</div>

What is *like* a promise but can resolve mutliple times?

I am looking for a pub/sub mechanism that behaves like a promise but can resolve multiple times, and behaves like an event except if you subscribe after a notification has happened it triggers with the most recent value.
I am aware of notify, but deferred.notify is order-sensitive, so in that way it behaves just like an event. eg:
d.notify('notify before'); // Not observed :(
d.promise.progress(function(data){ console.log(data) });
d.notify('notify after'); // Observed
setTimeout(function(){ d.notify('notify much later') }, 100); // Also Observed
fiddle: http://jsfiddle.net/foLhag3b/
The notification system I'd like is a good fit for a UI component that should update to reflect the state of the data behind it. In these cases, you don't want to care about whether the data has arrived yet or not, and you want updates when they come in.
Maybe this is similar to Immediate mode UIs, but is distinct because it is message based.
The state of the art for message based UI updating, as far as I'm aware, is something which uses a promise or callback to initialize, then also binds an update event:
myUIComponent.gotData(model.data);
model.onUpdate(myUIComponent.gotData); // doing two things is 2x teh workz :(
I don't want to have to do both. I don't think anyone should have to, the use case is common enough to abstract.
model.whenever(myUIComponent.gotData); // yay one intention === one line of code
I could build a mechanism to do what I want, but I wanted to see if a pub/sub mechanism like this already exists. A lot of smart people have done a lot in CS and I figure this concept must exist, I just am looking for the name of it.
To be clear, I'm not looking to change an entire framework, say to Angular or React. I'm looking only for a pub/sub mechanism. Preferably an implementation of a known concept with a snazzy name like notifr or lemme-kno or touch-base.
You'll want to have a look at (functional) reactive programming. The concept you are looking for is known as a Behavior or Signal in FRP. It models the change of a value over time, and can be inspected at any time (continuously holds a value, in contrast to a stream that discretely fires events).
var ui = state.map(render); // whenever state updates, so does ui with render() result
Some popular libraries in JS are Bacon and Rx, which use their own terminology however: you'll find properties and observables.

How can I make my internet slower?

No really.
I have a lot of AJAX requests in my web app, and I want to include appropriate feedback mechanisms, spinners and the like for when the response is slow. But when developing all the calls are almost instant...
Using setTimeout inside your success handler can be one way. Suppose your callback for ajax completion is say function doneFn(..), then, change that callback to something like delayedDone(..) and from there call your original doneFn after a delay:
function delayedDone(){
setTimeout(function(){doneFn(responseParams);}, 3000);
}
And of course, another way would be to introduce some tiny milliseconds of sleep on the server side.
Here are two software solutions I have found - one for Mac and one for Windows:
http://wanem.sourceforge.net/
http://mschrag.github.com/
A rate limiting proxy might be what you're looking for. http://blog.nella.org/?p=833 shows an example, I'm not sure how complete it is. But the concept can easily be expanded on.

Why use event listeners over function calls?

I've been studying event listeners lately and I think I've finally gotten them down. Basically, they are functions that are called on another object's method. My question is, why create an event listener when calling the function will work just fine?
Example, I want to call player.display_health(), and when this is fired, the method player.get_health() should be fired and stored so that display_health() has access to it. Why should I use an event listener over simply calling the function? Even if display_health() were in another object, this still doesn't appear to be a problem to me.
If you have another example that fits the usage better, please let me know. Perhaps particular languages don't benefit from it as much? (Javascript, PHP, ASP?)
You might not always be in control of the code that's doing the calling. Or even if you are, you don't want to introduce dependencies into that code. In cases like that, it's better for the code to fire an event and allow the code you do control, or the code that should have the dependency, to listen for the event and act accordingly.
For example, perhaps you're creating a library that will be used by other people. They don't have the source code or in some way can't/shouldn't be able to modify it (or shouldn't have to). Your documentation states that specific events are raised under specific circumstances. They can then, in turn, respond to those events.
Or perhaps you have some domain libraries in your enterprise. You do control them and can modify them, but architecturally they're generally considered to be working as they currently are coded and shouldn't be changed. (Don't want to incur a round of QA to re-validate the updated code, the code belongs to another department and they don't want you to change it, etc.) And you're in the position where you want that code to be able to do different things in different circumstances/environments. If that code raises and event where relevant, you can hook your code into it (and/or swap out accordingly) without having to mess with that code.
Just a couple quick examples, I'm sure others have more.
My question is, why create an event listener when calling the function will work just fine?
What if you don't know what function you want to call?
Take the classic example, a Button that the user can click on. Whoever writes the library has no idea what function you want called when the button is clicked. It would also be pretty prohibitive if every Button could only call the same function when it is clicked.
So instead, you can attach an event handler to the event. Then when the event is triggered, the Button can do what it needs to, without having to know at compile-time exactly what function it's supposed to be calling.
In Brief, you can write the code without event listener, but using event listener help other to use the same code as library.
Even with the detailed answers above, I was still having trouble understanding what the actual difference was between using a controller / functions OR an event listener.
One of the things that has been left out in all of these answers is that the use of Events and Event Listeners comes in handy when you do not want to couple your code so closely. Each function, class, etc, should have singleness of purpose.
So say you are getting hit with an API request from an outsider. In my case, my exact problem understanding this concept was when I am receiving API calls from Stripe Webhooks.
The purpose of Stripe Webhooks is: say a customer spends $10,000 on your website. Your standard procedure is to Auth and Capture. Update DB to reflect their new membership status. In a perfect world, and in our company's case, 999/1000 times, this goes perfectly. Either their card is declined on the spot, or the payment goes through. In both cases, we send them an email letting them know.
But what about the 1/1000 time when the user pays and Stripe returns a Card Failure error (which can be a number of different things)? In our case, we email them and tell them the billing has failed. The problem we've encountered is that some BANKS are investigating large charges, which comes back as an Error, but then a few minutes later the bank authorizes the charges and the payment is captured.
So what is there to do? Enter Stripe Webhooks. Stripe Webhooks will hit an API endpoint if something like this occurs. Actually, Stripe Webhooks can hit your API any and every time a payment isn't instantly Authed, Captured, or if the customer asks for a refund.
This is where an Event Listener comes in handy. Stripe shoots over a POST with the customer info, as well as the Webhook type. We will now process that, update the database, and shoot them a success email.
But why not just use a standard route and controller?
The reason we don't just use a standard route and controller is because we would either need to modify the already defined functions, classes, etc, or create a new series of classes that are coupled together, such as -> Stripe API Calls Received, Update DB, Send Email. Instead of coupling these closely together, we use an Event Listener to first accept the API Call, then hit each of those Classes, Functions, etc., leaving everything uncoupled.
I looked everywhere, and I think the Laravel documentation explains it best. I finally understood when given a concrete example, and what the purpose of an Event Listener is:
Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an OrderShipped event, which a listener can receive and transform into a Slack notification.
https://laravel.com/docs/5.6/events
I think the main reason for events vs function calls is that events are 'listened to' while calls are 'made'. So a function call is always made to another object whereas listeners 'choose' to listen for an event to be broadcast from your object.
The observer pattern is a good study for this capability. Here is a brief node.js example which illustrates the concept:
var events = require('events');
var Person = function(pname) {
var name = pname;
};
var james = new Person('james');
var mary = new Person('mary');
var loudmouth = new Person('blabberer');
loudmouth.mouth = new events.EventEmitter();
//jame's observer.
james.read_lips = function(msg){
console.log("james found out: " + msg);
};
//james adds his event to the emitter's event listener.
james.enter_elevator = function(){
console.log('james is in the elevator');
//NOTE: james adds HIMSELF as a listener for the events that may
//transpire while he is in the elevator.
loudmouth.mouth.on('elevator gossip', james.read_lips)
};
//james removes his event from the emitter when he leaves the elevator.
james.leave_elevator = function(){
// read lips is how james responds to the event.
loudmouth.mouth.removeListener('elevator gossip', james.read_lips);
console.log('james has left the elevator');
};
//mary's observer
mary.overhear = function(msg){
console.log("mary heard: " + msg);
};
//mary adds her observer event to the emitter's event listeners
mary.enter_elevator = function(){
// overhear is how mary responds to the event.
console.log('mary is in the elevator');
//NOTE: now mary adds HERSELF to the listeners in the elevator and
//she observes using a different method than james which suits her.
loudmouth.mouth.on('elevator gossip', mary.overhear);
};
loudmouth.speaks = function(what_is_said){
console.log('loudmouth: ' + what_is_said);
this.mouth.emit('elevator gossip', what_is_said);
};
james.enter_elevator();
mary.enter_elevator();
loudmouth.speaks('boss is having an affair');
james.leave_elevator();
loudmouth.speaks('just kidding');
console.log('james did not hear the last line because he was not listening anymore =)');
so in this 'story' the actors choose to listen or when to not listen for events from a third party. I hope this helps.

Resources