Matteo Scandolo | 40f8fa9 | 2016-12-07 09:21:35 -0800 | [diff] [blame^] | 1 | import {Injectable} from '@angular/core'; |
| 2 | import {IWSEvent} from '../../interfaces/ws.interface'; |
| 3 | import {BehaviorSubject} from 'rxjs'; |
| 4 | import * as _ from 'lodash'; |
| 5 | |
| 6 | /** |
| 7 | * @whatItDoes Update a BehaviorSubject after receiving an event from an Observable |
| 8 | * @stable |
| 9 | */ |
| 10 | |
| 11 | @Injectable() |
| 12 | export 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 | } |