Skip to content

Commit

Permalink
perf: cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
tutkli committed Apr 29, 2024
1 parent 4b879e5 commit 4089c81
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions libs/ngx-breakpoint-observer/src/lib/observe-media-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,29 @@ import { effect, type Signal, signal, untracked } from '@angular/core';
* @param query
*/
export function observeMediaQuery(query: string): Signal<boolean> {
const isSupported = signal(
window && 'matchMedia' in window && typeof window.matchMedia === 'function'
);
const isSupported =
window && 'matchMedia' in window && typeof window.matchMedia === 'function';

let mediaQuery: MediaQueryList | undefined;
const matches = signal(false);

const cleanup = () => {
if (!mediaQuery) return;

mediaQuery.removeEventListener('change', update);
};

const update = () => {
if (!isSupported()) return;

if (!isSupported) return;
mediaQuery = window.matchMedia(query);
untracked(() => matches.set(!!mediaQuery?.matches));

if (!mediaQuery) return;

mediaQuery.addEventListener('change', update);
};

effect(onCleanup => {
update();
onCleanup(() => cleanup());
onCleanup(cleanup);
});

return matches.asReadonly();
Expand Down

0 comments on commit 4089c81

Please sign in to comment.