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 defer operator #330

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
30 changes: 30 additions & 0 deletions src/defer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Store, Unit, merge, sample } from 'effector';
import { combineEvents } from '../combine-events';
import { not } from '../not';

export interface DeferArgs {
clock: Unit<any>;
until: Store<boolean>;
}

export const defer = (args: DeferArgs) => {
const { clock, until: condition } = args;

const calledAfterCondition = sample({
clock: clock,
filter: condition,
});

const calledBeforeCondition = sample({
clock: clock,
filter: not(condition),
});

return merge([
Copy link
Contributor Author

@velialiev velialiev May 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there could be 4 cases:

  1. Event called, condition is true --> call event
  2. Event called, condition is false --> wait until condition will be true and call event
  3. Condition became true, event is not called yet --> wait until event is called
  4. Condition became false, event is not called yet --> reset the state and wait both for event and condition to become true

IMPORTANT: if clock will be called more than 1 time only the last event will be deferred and called. Other events will be ignored

calledAfterCondition,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if condition is already true then call event immediately

combineEvents({
events: [calledBeforeCondition, condition.updates.filter({ fn: Boolean })],
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if condition is not true yet then defer event call until condition became true

reset: condition.updates.filter({ fn: (value) => !value }),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if condition became true and then false we should reset combine events since event call should be deferred until condition will be true again

}),
]);
};
Loading