Skip to content

Commit

Permalink
feature: add setLoading rxjs operator function
Browse files Browse the repository at this point in the history
  • Loading branch information
Denis Platonov committed Mar 18, 2023
1 parent ee84f5b commit 15f998b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
31 changes: 31 additions & 0 deletions packages/rxjs/src/operators/set-loading.operator.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { BehaviorSubject, of, throwError } from 'rxjs';
import { delay } from 'rxjs/operators';
import { flipFlag } from './set-loading.operator';

describe('set-loading.operator.ts', () => {
let isLoading$: BehaviorSubject<boolean>;

beforeEach(() => {
isLoading$ = new BehaviorSubject<boolean>(false);
});

it('should set loading state to false after source completes', () => {
of('test')
.pipe(flipFlag(isLoading$))
.subscribe({
complete: () => {
expect(isLoading$.getValue()).toBe(false);
}
});
});

it('should set loading state to false after source errors', () => {
throwError('error')
.pipe(delay(10), flipFlag(isLoading$), delay(10))
.subscribe({
error: () => {
expect(isLoading$.getValue()).toBe(false);
}
});
});
});
12 changes: 12 additions & 0 deletions packages/rxjs/src/operators/set-loading.operator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { BehaviorSubject, defer, Observable, OperatorFunction } from 'rxjs';
import { finalize } from 'rxjs/operators';

export function flipFlag<T>(flagSubject$: BehaviorSubject<boolean>): OperatorFunction<T, T> {
const initialSubjectValue: boolean = flagSubject$.getValue();

return (source: Observable<T>): Observable<T> =>
defer(() => {
flagSubject$.next(!initialSubjectValue);
return source.pipe(finalize(() => flagSubject$.next(!!initialSubjectValue)));
});
}

0 comments on commit 15f998b

Please sign in to comment.