UNPKG

rxpoweredup

Version:

A Typescript RxJS-based library for controlling LEGO Powered UP hubs & peripherals.

34 lines (33 loc) 1.17 kB
import { Observable, take, takeUntil } from 'rxjs'; import { AttachIoEvent } from '../../constants'; export class AttachedIoRepliesCache { messages$; onDisconnected$; replies$; cacheMap = new Map(); constructor(messages$, onDisconnected$) { this.messages$ = messages$; this.onDisconnected$ = onDisconnected$; this.replies$ = new Observable((observer) => { if (this.cacheMap.size) { [...this.cacheMap.values()].forEach((message) => { observer.next(message); }); } const sub = this.messages$.subscribe((reply) => { observer.next(reply); }); return () => sub.unsubscribe(); }); this.messages$.pipe(takeUntil(this.onDisconnected$)).subscribe((reply) => this.addReply(reply)); this.onDisconnected$.pipe(take(1)).subscribe(() => this.cacheMap.clear()); } addReply(reply) { if (reply.event === AttachIoEvent.Detached) { this.cacheMap.delete(reply.portId); } else { this.cacheMap.set(reply.portId, reply); } } }