refactor: remove nested subscription

This commit is contained in:
waterplea
2022-06-21 13:28:27 +03:00
parent e138b88e75
commit 0a72ceb1da

View File

@@ -1,4 +1,5 @@
import { merge, Observable, ReplaySubject, Subject, Subscription } from 'rxjs' import { merge, Observable, ReplaySubject, Subject } from 'rxjs'
import { switchMap } from 'rxjs/operators'
import { Store } from './store' import { Store } from './store'
import { DBCache, Http } from './types' import { DBCache, Http } from './types'
import { RPCError } from './source/ws-source' import { RPCError } from './source/ws-source'
@@ -10,22 +11,20 @@ export class PatchDB<T> {
public rpcError$ = new Subject<RPCError>() public rpcError$ = new Subject<RPCError>()
public cache$ = new ReplaySubject<DBCache<T>>(1) public cache$ = new ReplaySubject<DBCache<T>>(1)
private updatesSub?: Subscription private sub = this.sources$.pipe(
private sourcesSub = this.sources$.subscribe(sources => { switchMap(sources => merge(...sources.map(s => s.watch$(this.store)))),
this.updatesSub = merge(...sources.map(s => s.watch$(this.store))).subscribe({ ).subscribe({
next: (res) => { next: (res) => {
if ('result' in res) { if ('result' in res) {
this.store.update(res.result) this.store.update(res.result)
this.cache$.next(this.store.cache) this.cache$.next(this.store.cache)
} } else {
else { this.rpcError$.next(res)
this.rpcError$.next(res) }
} },
}, error: (e) => {
error: (e) => { this.connectionError$.next(e)
this.connectionError$.next(e) },
},
})
}) })
constructor ( constructor (
@@ -35,7 +34,6 @@ export class PatchDB<T> {
) { } ) { }
clean () { clean () {
this.sourcesSub.unsubscribe() this.sub.unsubscribe()
this.updatesSub?.unsubscribe()
} }
} }