Skip to content

Commit efb46ec

Browse files
committed
feat(util-rxjs): add finalizeWithLatest operator
1 parent 17afde8 commit efb46ec

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Observable, finalize, tap } from 'rxjs';
2+
3+
export const finalizeWithLatest =
4+
<T>(callback: (latest: T | null) => void) =>
5+
(value$: Observable<T>) => {
6+
let latest: T | null = null;
7+
return value$.pipe(
8+
tap((value) => (latest = value)),
9+
finalize(() => callback(latest))
10+
);
11+
};

packages/util-rxjs/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ export * from './TrackerSubject';
22
export * from './blockingWithLatestFrom';
33
export * from './toEmpty';
44
export * from './passthrough';
5+
export * from './finalizeWithLatest';
56
export * from './types';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { EMPTY, from, lastValueFrom } from 'rxjs';
2+
import { finalizeWithLatest } from '../src';
3+
4+
describe('finalizeWithLatest', () => {
5+
describe('source completes without emitting', () => {
6+
it('calls the callback function with "null"', async () => {
7+
const callback = jest.fn();
8+
EMPTY.pipe(finalizeWithLatest(callback)).subscribe();
9+
expect(callback).toBeCalledWith(null);
10+
});
11+
});
12+
13+
describe('source emits some value(s)', () => {
14+
it('calls the callback function with last emitted value', async () => {
15+
const callback = jest.fn();
16+
await lastValueFrom(from([1, 2]).pipe(finalizeWithLatest(callback)));
17+
expect(callback).toBeCalledWith(2);
18+
});
19+
});
20+
});

0 commit comments

Comments
 (0)