I've been struggling to transform a snippet of code into a custom rxjs operator, but I'm facing difficulties making it function correctly.
Here is the current implementation of my custom operator:
export const isLastItemTheSame = (oldValue: any[], key: string, condition: boolean) => {
return condition ? <T>(obsv: Observable<T[]>) => obsv.pipe(
filter(newValue => {
try {
return (oldValue[oldValue.length - 1][key] === newValue[newValue.length - 1][key]);
}
catch(err) {
return false;
}
}),
mapTo(true)
) : <T>(obsv: Observable<T>) => obsv.pipe(ignoreElements());
};
This custom operator aims to compare the last items in two lists - old and new. If they match, the success callback of the subscribe
should not trigger. However, if they do not match, it should fire.
The challenges I am currently facing include:
- The segment
is not functioning as expected and does not initiate the success callback.<T>(obsv: Observable<T>) => obsv.pipe(ignoreElements())
- When the
condition
is set totrue
, the operator returns a boolean instead of the new list. Consequently, binding the new list tothis.items
in the subscribe success callback becomes unfeasible.
I am using this operator in the following manner:
const source$ = this.api.get<CustomResponse>('events');
source$.pipe(
first(),
tap((res) => this.total = res.totalsize || 0),
map((res) => res.list),
isLastItemTheSame(this.items, 'eventid', this.items.length && !isReset)
).subscribe((items: IEvent[]) => {
// if (this.items.length && !isReset) {
// if (items[items.length - 1].eventid === this.items[this.items.length - 1].eventid) {
// return;
// }
// }
this.items = isReset ? items : [...this.items, ...items];
}, (err) => {
if (err.status !== 401) {
this.router.navigate(['dashboard']).then(() => {
this.notifications.newNotification({message: this.translate.instant('NOTIFICATIONS.EVENTS.GET_LIST_ERROR'), theme: 'danger'});
});
}
}
);
The commented-out code within the block is what I aim to refactor, providing clarity on my objective.
How can I overcome these issues?