import { merge, Observable, ReplaySubject, Subject } from 'rxjs' import { switchMap } from 'rxjs/operators' import { Store } from './store' import { DBCache, Http } from './types' import { RPCError } from './source/ws-source' import { Source } from './source/source' export class PatchDB { public store: Store = new Store(this.http, this.initialCache) public connectionError$ = new Subject() public rpcError$ = new Subject() public cache$ = new ReplaySubject>(1) private sub = this.sources$.pipe( switchMap(sources => merge(...sources.map(s => s.watch$(this.store)))), ).subscribe({ next: (res) => { if ('result' in res) { this.store.update(res.result) this.cache$.next(this.store.cache) } else { this.rpcError$.next(res) } }, error: (e) => { this.connectionError$.next(e) }, }) constructor ( private readonly sources$: Observable[]>, private readonly http: Http, private readonly initialCache: DBCache, ) { } clean () { this.sub.unsubscribe() } }