I want to emit to the two different state in one stream,
Is there any methods beside using Future.delayed?
I try this:
on<AnEvent>((event, emit) async {
emit(somethingState1());
await Future.delayed(const Duration(milliseconds: 5));
emit(somethingState2());
}
If i didn’t use future delayed, bloc only stream the second emit, it is replace the first emit. But if i use future delayed, i don’t know how long the first emit need to stream. it is not efficient.
Maybe there is method like listen the first emit, if checked already send and arrive, automatically trigger the second emit.
3
Answers
You are misunderstanding how the stream and bloc working.
emit(someState1)
.emit(someState2)
.await Future.delayed()
, it could beawait http.callLoginRequest()
, it could be anything.Action "pull the trigger", or
emit(someStateXX)
is JUST AN ACTION to tell your UI shows loading widget or success/fail dialog or anything.Back to your question:
emit(somethingState1());
: Tell your UI shows loading widget.await doSomething()
: Do some logic here, like you said: "checked already send and arrive".emit(somethingState2());
: After logic completed, tell UI to update success/fail dialog.If you don’t use
await Future.delayed()
, orawait doSomething()
, it just like you are using a machine gun. 2 bullets were injected out of barrel almost immediately makes us feel 2 bullets come through at the same time. In your Flutter, it may be happens in micro-seconds and cause to our misunderstanding.The states update too fast and the app doesn’t have time to listen to the first one because immediatelly the second one is triggerd. You can put even a smaller delay i think and it won’t really affect the app, but will help you with what you want to achieve
Emitter provides
.forEach
method that can be used to emit multiple state. There will be some business logic in stream.