I m performing crud operation on certain array in angular. I am kind of experimenting with rxjs, in order to learn it more. It is my person facade below.
PersonFacade.ts
private readonly modifyPersonSubject = new Subject<{
person: Person;
action: actionType;
}>();
people$ = this.personService.getPeople().pipe(
switchMap((initialPeople) =>
this.modifyPersonSubject.pipe(
// emmiting starting values
startWith({ person: {} as Person, action: "None" as actionType }),
scan((acc, curr) => {
if (curr.action === "None") return acc;
if (curr.action === "Add")
return this.handleAddPerson(acc, curr.person);
if (curr.action === "Delete")
return this.handleDelete(acc, curr.person);
if (curr.action === "Update")
return this.handleUpdate(acc, curr.person);
return acc;
}, of([...initialPeople]))
)
)
);
handleAddPerson(acc: Observable<Person[]>, person: Person) {
return this.personService.createPerson(person).pipe(
catchError((error) => {
console.log(error);
return NEVER;
}),
switchMap((res: Person) => {
// Update and return the accumulator with the new person
const updatedPeople = acc.pipe(map((a) => [...a, res]));
return updatedPeople; // Return the updated array as an observable
})
);
}
// handleDelete(), handleUpdate() are kind of similar.
Issue:
Initial list : ['Person1','Person2'] Whenever I am adding a person, it is working fine for first time. Suppose I have added 'John' first (now list is ['Person1','Person2','John']) Now, I add 'Mike' it (It is displaying ['Person1','Person2','John','Mike'] , while in the DB records are ['Person1','Person2','John','Mike','John']. If I refresh the tab, then we can see updated values from db). Now i add the 3rd value 'Max' . Records in view are ['Person1','Person2','John','Mike','John',Max] while in Db ['Person1','Person2','John','Mike','John',Max,Mike,John].
Similar kind of behavior happens with deleting. Whenever i add or remove a value, all the previously performed operations are also getting invoked again.
Does someone know about it?
If I do not make http call from Scan, and accumulate the Person[] not Observable<Person[]>, then everything works fine.
scan((acc, curr) => {
if (curr.action === "None") return acc;
if (curr.action === "Add")
return [...acc, curr.person]
return acc;
}, [...initialPeople])
I am not able to understand, how it has cached previous operations. I can go with ngrx/ngrx component store/ signals. But I am trying to improve rxjs skills here. Does anyone know about it?