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

Feature Suggestion: waitForSignal #476

Open
ShacharHarshuv opened this issue Jul 31, 2024 · 0 comments
Open

Feature Suggestion: waitForSignal #476

ShacharHarshuv opened this issue Jul 31, 2024 · 0 comments

Comments

@ShacharHarshuv
Copy link
Contributor

Hey! First of all - amazing library! I'm just looking over at these utilities and they look really strong! Some are things I had implemented myself (but your implementation is better) and some are things I haven't even thought that I need!

I had an idea that might fit your library (if it doesn't - no problem).

function waitForSignal<T, U extends T>(
    value: Signal<T>,
    filter: (value: T) => value is U,
  ): Promise<U>;

An example use-case would be if you have a signal with a loading state, but you want to wait for a loaded value:

const loadedValue = await waitForSignal(data, data => data.isLoaded).then(data => data.value);

Here's an example implementation of this:

export function injectWaitForSignal() {
  const injector = inject(Injector);

  return function waitForSignal<T, U extends T>(
    value: Signal<T>,
    filter: (value: T) => value is U,
  ) {
    return new Promise<U>((resolve) => {
      const effectRef = effect(
        () => {
          const v = value();
          if (filter(v)) {
            resolve(v);
            effectRef.destroy();
          }
        },
        {
          injector,
        },
      );
    });
  };
}

I wrapped it in an injection function, because a) I need an injection context, and b) it's unlikely that the consumer will have that injection context when they want to call it, if there are multiple awaits. I feel like that simplifies things for the consumer as they can call it in the beginning and then use the function as many time as they want.

@ShacharHarshuv ShacharHarshuv changed the title Feature Suggestion: awaitForSignal Feature Suggestion: waitForSignal Jul 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant