From 259786ad98eabecf1ca7cfc65481acb0080abd09 Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Tue, 16 Jul 2019 12:48:38 +0300 Subject: [PATCH] Added the base Pin class --- src/modules/simulation/classes/Pin.ts | 43 +++++++++++++++++++ .../simulation/types/SubscriptionData.ts | 6 +++ 2 files changed, 49 insertions(+) create mode 100644 src/modules/simulation/classes/Pin.ts create mode 100644 src/modules/simulation/types/SubscriptionData.ts diff --git a/src/modules/simulation/classes/Pin.ts b/src/modules/simulation/classes/Pin.ts new file mode 100644 index 0000000..4b48da7 --- /dev/null +++ b/src/modules/simulation/classes/Pin.ts @@ -0,0 +1,43 @@ +import { SubscriptionData } from '../types/SubscriptionData' +import { BehaviorSubject } from 'rxjs' + +export class Pin { + public state = new BehaviorSubject(false) + public connectedTo = new Set() + + private pairs = new Set() + private subscriptions: SubscriptionData[] = [] + + public addPair(pin: Pin) { + this.pairs.add(pin) + + const rawSubscription = pin.state.subscribe(state => { + this.state.next(state) + }) + + this.subscriptions.push({ + data: pin, + subscription: rawSubscription + }) + } + + public removePair(pin: Pin) { + this.pairs.delete(pin) + + for (const subscription of this.subscriptions) { + if (subscription.data === pin) { + subscription.subscription.unsubscribe() + } + } + + this.subscriptions = this.subscriptions.filter( + subscription => subscription.data !== pin + ) + } + + public dispose() { + for (const subscription of this.subscriptions) { + subscription.subscription.unsubscribe() + } + } +} diff --git a/src/modules/simulation/types/SubscriptionData.ts b/src/modules/simulation/types/SubscriptionData.ts new file mode 100644 index 0000000..28c903c --- /dev/null +++ b/src/modules/simulation/types/SubscriptionData.ts @@ -0,0 +1,6 @@ +import { Subscription } from 'rxjs' + +export interface SubscriptionData { + subscription: Subscription + data: T +}