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

withResource awaits sync callback #32

Open
kinex opened this issue Aug 26, 2019 · 1 comment
Open

withResource awaits sync callback #32

kinex opened this issue Aug 26, 2019 · 1 comment

Comments

@kinex
Copy link

kinex commented Aug 26, 2019

withResource is defined as:
Future<T> withResource<T>(FutureOr<T> Function() callback)

Method body has this line:
return await callback();

From my understanding the correct way to write that is something like:

final result = callback();
if (result is Future<T>) {
  return await result;
} else {
  return result;
}

I found this while searching how to use FutureOr<T> correctly. Current code in Pool is not a good sample to follow, or am I missing something?

@nioncode
Copy link

await can be used on Future<T> as well as on T directly, i.e. it is perfectly fine to await a synchronous value (it will be wrapped into a Future under the hood).

That said, using await will always introduce an asynchronous gap and yield execution back to the event loop, which will introduce a delay in processing if used unnecessarily in a tight-loop, but I don't think this optimization is needed in this case.

See also: https://stackoverflow.com/questions/59213196/what-is-the-purpose-of-futureor

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

2 participants