rxjs-socket.io
v0.3.9
Published
wraps socket.io-client into replay subjects called ioEvents
Downloads
6
Readme
RxJs SocketIO
An abstraction of socket-io with RxJs, it does this by separating the concerns of connection and event handling into two, IO
and ioEvent
.
Installation
$ npm install --save rxjs-socket.io
Quickstart
import {IO} from 'rxjs-socket.io';
// Assign a provider for the RxJs-Socket.io class
const Socket = new IO();
// Listen to and subscribe to an event
Socket.listenToEvent('event-name').event$.subscribe(data => console.log('event-name data:', data));
// Connect
Socket.connect(`http://localhost:1337`);
In depth
import {IO, ioEvent} from 'rxjs-socket.io';
import {merge} from 'rxjs';
import {filter, map, takeUntil} from 'rxjs/operators';
// Assign a provider for the RxJs-Socket.io class
const Socket = new IO();
// Assign a pointer to the connection Observable, it will be hot when we connect. it's cold until then.
const connection = Socket.event$;
// Create an assignment to the pipe of the sockets' connection which emits only when we are disconnected
const connectedClosed$ = connection.pipe(filter(({connected}) => !connected));
// Create new Events to be listened to
const HelloWorldEvent = new ioEvent(`HelloWorld`);
const FooBar = new ioEvent('FooBar');
// (optional) assign the cold obserables to a variable
const HelloWorldEvent$ = HelloWorldEvent.event$;
// Do fancy stuff with the Subjects provided
merge(
...[HelloWorldEvent, FooBar]
.map(({name, event$}) =>
event$.pipe(map(data => ({name, data})))))
.pipe(takeUntil(connectedClosed$))
.subscribe(({name: eventName, data: eventData}) => {
console.log(`event: ${eventName}, data: ${JSON.stringify(eventData)}`);
});
// Or do some more basic stuff,
HelloWorldEvent$.subscribe(data => console.log(`HelloWorldEvent$:`, data));
// Finally, listen and connect to the provided events
Socket.listenToEvent(HelloWorldEvent);
Socket.listenToEvent(FooBar);
Socket.connect(`http://localhost:1337`);
// You can make events and hook them later too!
const BarFoo = new ioEvent(`BarFoo`);
// You can even mess up the order on the listening and subscribing
Socket.listenToEvent(BarFoo);
BarFoo.event$.subscribe(data => console.log(`BarFoo`, data));
// If you don't need the pointer to the event to refer to it later,
Socket.listenToEvent(new ioEvent<string>(`FooBarBarFoo`)).event$.subscribe(data => console.log(`FooBarBarFoo`, data));
// And you can deconstruct the creation of new ioEvents and get their observables
const [foo, bar, baz] = Socket.listen(['foo', 'bar', 'baz']);
merge(foo, bar, baz).subscribe(data => console.log(`foo, bar, baz`, data));
// IF you need a side-effect but don't want to subscribe you can always access
BarFoo.onUpdate = (newState) => console.log(`BarFoo newState`, newState);
| links | | |--- |--- | | repo | https://gitlab.com/moshmage/rxjs-socket.io/ | | examples | -todo- | | documentation | https://moshmage.gitlab.io/rxjs-socket.io/