Skip to content

Instantly share code, notes, and snippets.

@teyfix
Last active June 20, 2021 12:39
Show Gist options
  • Select an option

  • Save teyfix/0571b6753f25b4a80c564bcb62225246 to your computer and use it in GitHub Desktop.

Select an option

Save teyfix/0571b6753f25b4a80c564bcb62225246 to your computer and use it in GitHub Desktop.
rxjs - detailed socket.io
import { fromEvent, Subject } from 'rxjs';
import { map, shareReplay, switchMap } from 'rxjs/operators';
import io from 'socket.io-client';
const $token = new Subject();
const $client = $token.pipe(
map((token) => {
if (null == token || '' === token) {
return {};
}
return {
transportOptions: {
polling: {
extraHeaders: {
authorization: 'Bearer ' + token,
},
},
},
};
}),
map((config) => io('/', config).connect()),
shareReplay(1),
);
const listen = (event) =>
$client.pipe(
switchMap((client) => fromEvent(client, event)),
shareReplay(1),
);
listen('message').subscribe((message) =>
console.log(message.author + ': ' + message.content),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment