blob: 80e8e059c676963f667ceef244ae648c01594f59 [file] [log] [blame]
Matteo Scandolo40f8fa92016-12-07 09:21:35 -08001import {Injectable} from '@angular/core';
2import {IWSEvent} from '../../interfaces/ws.interface';
3import {BehaviorSubject} from 'rxjs';
4import * as _ from 'lodash';
5
6/**
7 * @whatItDoes Update a BehaviorSubject after receiving an event from an Observable
8 * @stable
9 */
10
11@Injectable()
12export class ObservableCollectionHandler {
13
14 static update(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any> {
15 const collection: any[] = subject.value;
16
17 const index: number = _.findIndex(collection, (i) => {
18 return i.id === event.msg.object.id;
19 });
20 const exist: boolean = index > -1;
21 const isDeleted: boolean = _.includes(event.msg.changed_fields, 'deleted');
22
23 // remove
24 if (exist && isDeleted) {
25 _.remove(collection, {id: event.msg.object.id});
26 }
27 // Replace item at index using native splice
28 else if (exist && !isDeleted) {
29 collection.splice(index, 1, event.msg.object);
30 }
31 // if the element is not deleted add it
32 else if (!exist && !isDeleted) {
33 collection.push(event.msg.object);
34 }
35
36 subject.next(collection);
37
38 return subject;
39 }
40}