Technology background: Angular (4) with RxJS in TypeScript. But I believe problem is quite technology independent.
I have an array of elements. That array is provided by service, possibly from remote API (backend).
ElementService:
private elements: Element[];
private elementsSource = new ReplaySubject<Element[]>(1);
elementsObservable$ = this.elementsSource.asObservable();
Component subscribes to that observable and populates HTML list with data. Now each element of the list can be independly edited by user. After edit change must be saved and sent to a) backend, b) other components that subscribe for changes of that elements.
Because list elements may be edited and they can be "dirty", I don't want to show changes right away with 2-way data binding in other components. Because of this I copy output of observable and work on this copy, and then send update with new list to the service.
ElementListComponent:
elements: Element[];
constructor(private elementService: ElementService) { }
ngOnInit() {
this.subscribeElements();
}
private subscribeElements() {
this.elementService.getElements().subscribe(elements => this.elements = clone(elements));
}
private onChangeSave() {
this.elementService.updateElements(clone(this.elements));
}
But elements list can be also edited in other components / by other users. In such case ElementService will get update by websocket with new data. This will be sent to ElementListComponent by observable.
Now if:
- user A will start editing one or more items and user B will update some other elements, or
- user will start editing one element X in one component and then edit element Y in other component, or
- user will start editing elements X and Y, save changes to element X (save buttons are independent for elements on the list),
then unsaved changes will be lost as list will be replaced by new, updated one.
I thought about iterating over the array in subscribe() and updating every element separately in local array - adding new elements, removing missing ones, updating changed if they are not edited right now. This way the reference to the array would not change and dirty elements would not be "resetted".
Is this really the best way? Or am I missing something?
Aucun commentaire:
Enregistrer un commentaire