I’m using Flutter with flutter_bloc, and I’m in front of the following scenario.
Scenario
I have a Cubit with two methods beings loadFoo
and loadBar
:
class UserCubit extends Cubit<UserState> {
UserCubit() : super(UserState());
Future loadFoo() async {
emit(state.copyWith(
foo: await fancyApiService.loadFoo()
));
}
Future loadBar() async {
emit(state.copyWith(
bar: await fancyApiService.loadBar()
));
}
}
Then, in a StatefulWidget
I have the following:
@override
void initState() {
context.read<UserCubit>()..loadFoo()..loadBar();
super.initState();
}
What happens
loadFoo
is the first method to complete its execution and emit a new state.
In executing loadBar
, this.state
doesn’t contain the value provided by loadFoo
.
A possible solution
I noticed that by rewriting the methods code this way, it works properly. But shouldn’t it give the same results as the code mentioned above?
I guess this has something to do with the way Dart works behind the scenes (?).
Future loadFoo() async {
final foo = await fancyApiService.loadFoo();
emit(state.copyWith(
foo: foo
));
}
Future loadBar() async {
final bar = await fancyApiService.loadBar();
emit(state.copyWith(
bar: bar
));
}
2
Answers
This code:
is equivalent to:
Just to be clear, you have two unawaited async calls.
In the first version
loadFoo
andloadBar
will read the samestate
because An async function runs synchronously until the first await keyword and theawait
calls that will suspend the functions happen after reading the state. The execution flow will look like this:cubit.loadFoo()
state
inloadFoo
loadFoo
atawait fancyApiService.loadFoo()
cubit.loadBar()
state
inloadBar
loadBar
atawait fancyApiService.loadBar()
At this point
fancyApiService.loadFoo()
andfancyApiService.loadBar()
are both scheduled and execution flow will depend on which one completes first but theemit
incubit.loadFoo
orcubit.loadBar
will use the same state in either case.In your second version of
loadFoo
andloadBar
theawait
happens before reading the state so once again,fancyApiService.loadFoo()
andfancyApiService.loadBar()
are both scheduled and the execution flow will continue depending on which call completes first. The difference is that now thestate
is read after theasync
call so one ofcubit.loadFoo
andcubit.loadBar
will get a chance toemit
before the other reads the state.If your intention is to call
loadBar
afterloadFoo
completes you should at leastawait loadBar()
.Here are the methods, theoretically it’s supposed to work, just try:
These methods are asynchronous methods, but they don’t return any thing just
void
. so it’s unnecessary toawait
on their call, actually it may produce an error becauseawait
can only be used when the return type isFuture<AnyThing>
and, Here’s the initState method, no need to await: