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 +}