Skip to content

Listeners cannot be immediately triggered upon addition #2435

@markerikson

Description

@markerikson

Listeners always run in response to a dispatched action, but this means there's no way to trigger one immediately. (Imagine a longer-running workflow, where we don't even care about what the triggering action might be, but just want to start running and doing other work as soon as the listener is defined.)

Perhaps we could add a runImmediately: boolean option to the startListening options? In that case you'd probably get either no action passed into the listener, or some kind of a dummy action.

The alternative is to write your listener in such a way that you end up dispatching an action just to trigger it. Which is a valid thing to do, but also annoying.

Example of that from https://codesandbox.io/s/listen-for-condition-1b1b6g?file=/src/index.ts :

const listenForCondition = <State>(
  actionType: string,
  predicate: AnyListenerPredicate<State>,
  timeout?: number
): ThunkAction<
  ReturnType<ConditionFunction<State>>,
  State,
  unknown,
  AnyAction
> => (dispatch) =>
  new Promise<boolean>((resolve, reject) => {
    dispatch(
      addListener({
        type: actionType,
        effect: (_, { condition, unsubscribe }) =>
          condition(predicate as AnyListenerPredicate<unknown>, timeout)
            .then(resolve)
            .catch(reject)
            .finally(unsubscribe),
      })
    );
    dispatch({ type: actionType });
  });

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions