Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add watch operator #336

Merged
merged 2 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './defs/index.js';
export * from './manager.js';
export * from './operators/index.js';
export * from './refs/index.js';
export * from './stores/index.js';
1 change: 1 addition & 0 deletions src/operators/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './watch.js';
20 changes: 20 additions & 0 deletions src/operators/watch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { OffFn } from '@jujulego/event-tree';

import { Ref } from '../refs/index.js';

// Types
export type WatchCleanUp = () => void;
export type WatchFn<D> = (data: D) => WatchCleanUp | undefined;

// Operator
export function watch$<D>(ref: Ref<D>, fn: WatchFn<D>): OffFn {
let cleanUp: WatchCleanUp | undefined;

return ref.subscribe((data: D) => {
if (cleanUp) {
cleanUp();
}

cleanUp = fn(data);
});
}
42 changes: 42 additions & 0 deletions tests/operators/watch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { vi } from 'vitest';

import { var$, watch$ } from '@/src/index.js';

// Tests
describe('watch$', () => {
it('should call fn when the reference changes', () => {
const ref = var$<number>();
const fn = vi.fn();

watch$(ref, fn);
ref.mutate(42);

expect(fn).toHaveBeenCalledWith(42);
});

it('should call cb before next fn call', () => {
const ref = var$<number>();
const cb = vi.fn();

watch$(ref, () => cb);
ref.mutate(41);

expect(cb).not.toHaveBeenCalled();

ref.mutate(42);

expect(cb).toHaveBeenCalled();
});

it('should not call fn if off has been called', () => {
const ref = var$<number>();
const fn = vi.fn();

const off = watch$(ref, fn);
off();

ref.mutate(42);

expect(fn).not.toHaveBeenCalled();
});
});