ngneat/elf

async emitOnce

LoaderB0T opened this issue · 6 comments

Which @ngneat/elf-* package(s) are relevant/releated to the feature request?

@ngneat/elf

Description

emitOnce(() => ...) currently only supports synchronous actions.

Passing an async function that returns a promise, emitOnce will not wait until the function is resolved.

In our case, we have a fairly complex update method:

  1. update the store synchronously
  2. Do an HTTP call based on the change
  3. Change the store again with the results from the call
  4. Emit changes

Currently, this does not work as the changes are already emitted after step 1, because emitOnce does not await the callback.

Proposed solution

Provide a new emitOnceAsync function that only accepts callbacks that return Promises and awaits them before calling batchInProgress.next(false);

Alternatives considered

Adjust the existing emitOnce function to automatically handle promises internally if a promise is provided.
However this would probably be a breaking change in some apps, however it might be the expected behavior in the first place.

I am willing to provide a PR for both solutions.

Do you want to create a pull request?

Yes

The question is what happens if you update the state again afterwards.

Wdym afterwards? After the async operation is done or after it started before it is done?

If a second emitOnce is called before the first one is done, it will execute the action (Just like it works atm).
If a second emitOnceAsync is called it would now wait for both to finish I would say.

Or emitOnceAsync has to be rebranded to make it clear that nesting is not allowed to retain simplicity.

If you'll update the store in any place afterwards it'll not be updated until your async operation is done.

I mean, yeah, that is kinda the whole idea :)

It seems risky to me, but I don't mind to see a PR as long as we mention this in the docs.

Cool, I will try to come up with something in the next few hours.