Skip to content

Instantly share code, notes, and snippets.

@kino6052
Created August 1, 2020 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kino6052/bf7b66a80fcbd07bbe2dbfae048f3fdf to your computer and use it in GitHub Desktop.
Save kino6052/bf7b66a80fcbd07bbe2dbfae048f3fdf to your computer and use it in GitHub Desktop.
export class BroadcastingAgent {
// Participants
public participants: string[] = [];
// Subjects
public addParticipantSubject = new Subject<string>();
public removeParticipantSubject = new Subject<string>();
private commSubject: Subject<IMessage<unknown>>;
constructor(
public id: string = generateId(4, 4),
communicationChannel: Subject<IMessage<unknown>>
) {
this.commSubject = communicationChannel;
this.getCommSubject().subscribe(this.messageHandler);
this.getCommSubject().subscribe(this.greetingHandler);
}
// Messaging Utils
getCommSubject = () =>
this.commSubject.pipe(filter(({ id: _id }) => _id !== this.id));
getIndividualMessageCommSubject = () =>
this.getCommSubject().pipe(filter(({ to }) => to === this.id));
messageHandler = (message: IMessage<unknown>) => {
console.warn(message);
};
sendIndividualRequest = <T>(data: T, to: string) => {
this.commSubject.next({
id: this.id,
type: "individual",
data,
to,
});
};
// Participants
addParticipant = (id: string) => {
this.participants.push(id);
this.addParticipantSubject.next(id);
};
removeParticipant = (id: string) => {
let participants = this.getParticipants();
participants = participants.filter((_id) => _id !== id);
this.removeParticipantSubject.next(id);
};
getParticipants = () => {
const participants = [...this.participants];
return participants;
};
// Salutations
greetingHandler = (message: IMessage<unknown>) => {
const { id, type } = message;
const participants = this.getParticipants();
if (type !== "greeting") return;
if (participants.includes(id)) return;
console.warn(`ID: ${this.id}, Add Participant`);
this.addParticipant(id);
setTimeout(this.sendGreeting, 100);
};
farewellHandler = (message: IMessage<unknown>) => {
const { id, type } = message;
const participants = this.getParticipants();
if (type !== "farewell") return;
if (participants.includes(id)) return;
this.removeParticipant(id);
};
sendGreeting = () => {
this.commSubject.next({
id: this.id,
type: "greeting",
data: {},
});
};
sendFarewell = () => {
this.commSubject.next({
id: this.id,
type: "farewell",
data: {},
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment