I have a scenario where I need to avoid redundant computations if the subscription emits the same object.
this.stateObject$
.pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 })))
.subscribe(obj => heavyComputeTask(obj))
The current implementation may fail if the order of keys changes and is not efficient either.
How can I optimize this code?
In addition, to prevent repeating the same code, I intended to create a custom filter pipe like this:
export function ignoreUnChanged<T>(source: Observable<T>): Observable<T> {
return source.pipe(
distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 })
))
}
However, TypeScript throws an error stating that 'MonoTypeOperatorFunction<T>' is not compatible with 'OperatorFunction<T, T>'. Is there a more effective way to resolve this issue?
Thank you in advance.