Skip to content

Commit

Permalink
Merge pull request #118 from luii/feat/injectIs-helpers
Browse files Browse the repository at this point in the history
feat(query): 🔥 add `injectIsMutating` and `injectIsFetching`
  • Loading branch information
NetanelBasal authored Nov 5, 2023
2 parents c2f70ab + aa3881d commit 5505099
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
40 changes: 40 additions & 0 deletions query/src/lib/is-fetching.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { notifyManager, type QueryFilters } from '@tanstack/query-core';
import { injectQueryClient } from './query-client';
import { inject, Injectable, InjectionToken } from '@angular/core';
import { distinctUntilChanged, Observable } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';

@Injectable({ providedIn: 'root' })
export class IsFetching {
private queryClient = injectQueryClient();

use(filters?: QueryFilters) {
const result$ = new Observable<number>((observer) => {
observer.next(this.queryClient.isFetching(filters));
const disposeSubscription = this.queryClient.getQueryCache().subscribe(
notifyManager.batchCalls(() => {
observer.next(this.queryClient.isFetching(filters));
})
);

return () => disposeSubscription();
}).pipe(distinctUntilChanged());

return {
result$,
toSignal: () => toSignal(result$),
};
}
}

const UseIsFetching = new InjectionToken<IsFetching['use']>('UseIsFetching', {
providedIn: 'root',
factory() {
const isFetching = new IsFetching();
return isFetching.use.bind(isFetching);
},
});

export function injectIsFetching() {
return inject(UseIsFetching);
}
40 changes: 40 additions & 0 deletions query/src/lib/is-mutating.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { type MutationFilters, notifyManager } from '@tanstack/query-core';
import { injectQueryClient } from './query-client';
import { inject, Injectable, InjectionToken } from '@angular/core';
import { distinctUntilChanged, Observable } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';

@Injectable({ providedIn: 'root' })
export class IsMutating {
private queryClient = injectQueryClient();

use(filters?: MutationFilters) {
const result$ = new Observable<number>((observer) => {
observer.next(this.queryClient.isMutating(filters));
const disposeSubscription = this.queryClient.getMutationCache().subscribe(
notifyManager.batchCalls(() => {
observer.next(this.queryClient.isMutating(filters));
})
);

return () => disposeSubscription();
}).pipe(distinctUntilChanged());

return {
result$,
toSignal: () => toSignal(result$),
};
}
}

const UseIsMutating = new InjectionToken<IsMutating['use']>('UseIsFetching', {
providedIn: 'root',
factory() {
const isMutating = new IsMutating();
return isMutating.use.bind(isMutating);
},
});

export function injectIsMutating() {
return inject(UseIsMutating);
}

0 comments on commit 5505099

Please sign in to comment.