skip to Main Content

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


  1. You are misunderstanding how the stream and bloc working.

    • Imagine you have a pistol, the barrel is stream and each bullet is a state.
    • You pull the trigger first time, you emit(someState1).
    • You pull the trigger second time, you emit(someState2).
    • The period between 2 actions above, is how your your bullet was impacted, explodes, and ejected out of barrel = your business logic. It could be await Future.delayed(), it could be await 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(), or await 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. Emitter provides .forEach method that can be used to emit multiple state. There will be some business logic in stream.

    on<Add>((event, emit) async {
      Stream<int> stream = Stream.periodic(const Duration(seconds: 1), (i) => i);//your stream
      await emit.forEach(
        stream,
        onData: (data) {
          // dont need to wrap with `emit`,onData expect State in return
          if(data.isEven) StateA();      
          else StateB();
        },//it also provides  onError
      );
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search