Currently I am learning the bloc library for Flutter and I stumbled across this Function, I may be too unfamiliar with the exact implementation of Futures in Dart.
Here I am required to use the async keyword, since I am using await.
I would like to return an Item but am not allowed to, since I used the async keyword and have to return a Future.
Is the Item being wrapped up in a Future "artificially", because I've awaited already, so what is the point of the return type being a Future?
Does this result in a small overhead?
Future<Item> getItem(String id) async{
Item item = await _itemApiClient.getItemById(id);
return item;
}
With this implementation I am able to use "await" simply one time; when awaiting the getItem() function.
Future<Item> getItem(String id) {
Future<Item> item = _itemApiClient.getItemById(id);
return item;
}
CodePudding user response:
Your function is perfectly fine. I'd even do:
Future<Item> item(String id) => _itemApiClient.getItemById(id);
Yes, there is an overhead in having an async
function.
The async
function always creates its own Future
for its result, and there is an overhead moving the value from the getItemById
-returned future to the future returned by getItem
.
The overhead may or may not affect timing, depending on how the underlying futures are created. (It's possible that the value is propagated immediately when the first future completes, but there are no promises.) There is always a memory overhead.