Javascript Reactivity

September 15, 2024

Util Functions

Javascript Reactivity

Thuta Sann

Thuta Sann

Javascript Reactivity with IoT sensor network sample


Share This Snippet To :

A reactive system using Node.js and TypeScript without external libraries. We'll simulate an IoT sensor network where multiple sensors send temperature data to a server. This server uses a reactive system to automatically notify various subscribers when the temperature exceeds certain thresholds or changes significantly.

- You have multiple sensors collecting temperature data (e.g., from different rooms or devices).
- The system automatically reacts when:
- Temperature exceeds a critical threshold (e.g., 75°C).
- The temperature changes by more than a defined delta (e.g., ±5°C).

Source Code : https://github.com/thutasann/node-nest/tree/master/node-concepts/src/js-general/reactivity-samples/sensor-network

//------- reactive-sensor.ts type SensorSubscriber<T> = (newValue: T) => void; export class ReactiveSensor<T> { private value: T; private subscribers: SensorSubscriber<T>[] = []; constructor(newValue: T) { this.value = newValue; } subscribe(subscriber: SensorSubscriber<T>) { this.subscribers.push(subscriber); } set(newValue: T): void { if (this.value !== newValue) { this.value = newValue; this.notifySubscribers(); } } get(): T { return this.value; } private notifySubscribers(): void { this.subscribers.forEach((subscriber) => subscriber(this.value)); } } //------- sensor.ts import { ReactiveSensor } from './reactive-sensor'; export class Sensor { private temperature: ReactiveSensor<number>; constructor( private id: string, initialTemperature: number, ) { this.temperature = new ReactiveSensor<number>(initialTemperature); } public updateTemperature(newTemp: number) { console.log(`[Sensor ${this.id}] New temperature: ${newTemp}°C`); this.temperature.set(newTemp); } public onTemperatureChange(callback: (temp: number) => void) { this.temperature.subscribe(callback); } public getTemperature(): number { return this.temperature.get(); } } //------- alert-network.ts export class AlertSystem { public static checkCriticalTemperature( sensorId: string, temperature: number, ) { console.log('checkCriticalTemperature...'); if (temperature > 75) { console.log( `[ALERT] Sensor ${sensorId}: Critical temperature (${temperature}°C) exceeded!\n`, ); } } public static checkTemperatureDelta( sensorId: string, oldTemp: number, newTemp: number, ) { console.log('checkTemperatureDelta...'); const delta = Math.abs(newTemp - oldTemp); if (delta >= 5) { console.log( `[ALERT] Sensor ${sensorId}: Temperature changed significantly by ${delta}°C.\n`, ); } } } //------- app.ts import { AlertSystem } from './alert-network'; import { Sensor } from './sensor'; const sensor1 = new Sensor('LivingRoom', 22); const sensor2 = new Sensor('Kitchen', 30); sensor1.onTemperatureChange((newTemp) => { AlertSystem.checkCriticalTemperature('LivingRoom', newTemp); }); let lastTemperatureKitchen = sensor2.getTemperature(); sensor2.onTemperatureChange((newTemp) => { AlertSystem.checkCriticalTemperature('Kitchen', newTemp); AlertSystem.checkTemperatureDelta('Kitchen', lastTemperatureKitchen, newTemp); }); // Simulate temperature changes over time setTimeout(() => { sensor1.updateTemperature(25); // No alert sensor2.updateTemperature(80); // Alert: Critical temperature exceeded }, 1000); setTimeout(() => { sensor1.updateTemperature(28); // No alert sensor2.updateTemperature(85); // Alert: Critical temperature exceeded }, 2000); setTimeout(() => { sensor1.updateTemperature(34); // Alert: Temperature changed significantly sensor2.updateTemperature(72); // No alert }, 3000);

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?