import {Inject} from '@angular/core'; import {RecordCollection} from './record-collection'; import { Observable, Subject } from 'rxjs/Rx'; import _ from 'lodash'; import {RecordStoreService} from '../records/record-store.service'; export class RecordsProvider { sources: Observable[] = []; sourceAdded: Subject>; sourceRemoved: Subject>; constructor( @Inject(RecordStoreService) private recordStore: RecordStoreService) { this.sourceAdded = new Subject>(); this.sourceRemoved = new Subject>(); this._populateFromStore(recordStore); } add(collection: RecordCollection) : Observable { const obs = Observable.of(collection); this.sources.push(obs); this.sourceAdded.next(obs); this.recordStore.put(collection); return obs; } addSource(source: Observable) : Observable { const observable = Observable.create(obs => { source.subscribe({ next: rc => obs.next(rc), error: err => obs.error(err) }); }); this.sources.push(observable); this.sourceAdded.next(observable); source.subscribe(rc => this.recordStore.put(rc)); return observable; } removeSource(source: Observable) : Observable { const removedSource = _(this.sources) .remove(src => src === source) .head(); this.sourceRemoved.next(removedSource); removedSource.subscribe(col => { this.recordStore.remove(col); }); return removedSource; } private _populateFromStore(recordStore: RecordStoreService): void { recordStore.allDocs().subscribe(docs => { _.forEach(docs, rc => { const obs = Observable.of(rc); this.sources.push(obs); this.sourceAdded.next(obs); }); }); } }