Skip to content

Instantly share code, notes, and snippets.

@mohamedaboelmagd
Forked from NetanelBasal/dirty-check-11.ts
Created March 13, 2022 07:25
Show Gist options
  • Save mohamedaboelmagd/92f5275fb034c0f3ba68d979d45d9695 to your computer and use it in GitHub Desktop.
Save mohamedaboelmagd/92f5275fb034c0f3ba68d979d45d9695 to your computer and use it in GitHub Desktop.
export function dirtyCheck<U>(source: Observable<U>) {
let subscription: Subscription;
let isDirty = false;
return function <T>(valueChanges: Observable<T>): Observable<boolean> {
const isDirty$ = combineLatest(
source,
valueChanges,
).pipe(
debounceTime(300),
map(([a, b]) => {
return isDirty = isEqual(a, b) === false;
}),
finalize(() => subscription.unsubscribe()),
startWith(false),
shareReplay({ bufferSize: 1, refCount: true }),
);
subscription = fromEvent(window, 'beforeunload').subscribe(event => {
isDirty && (event.returnValue = false);
});
return isDirty$;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment