简体   繁体   中英

How to call parallel request in flutter Bloc

I am using BLoC in flutter .

As soon as BLoC instance is created I want to make to API calls. To achieve that, I have added the following code inside the constructor.

 class MyBloc extends Bloc<MyBlocEvent, MyBlocState> {

    MyBloc() {
        _repository = MyAccountRepository();
        _myAccountList = List();
        add(API1CallEevent());
        add(API2CallEevent());
      }
...  

and the event handling part

...  
     @override
      Stream<MyBlocState> mapEventToState(MyBlocEvent event) async* {
        if (event is API1CallEevent) {
    
       var ap1 =
              await _repository.getAPI1();
         ----
         ----
        }else if (event is API2CallEevent) {
    
      var api2 =
              await _repository.getAPI2();
       ----
       ---
        }
    
    }

The problem I am facing is that the API calls are not executed parallel, which means after API1CallEvent is completed then API2CallEvent get executed...

is there any way to do that in parallel?

In my opinion, doing two API calls in parallel and expecting result at the same time is not much related to BLoC.
It is better if each bloc-event triggers a specific set of actions, and events are decoupled from each other.

Additionally;
Instead of raising an event inside init block, it is better to do that when you init Bloc inside a provider. See example;

BlocProvider<AuthBloc>(
  lazy: false,
  create: (context) => AuthBloc(
    userRepository: _userRepository,
    )..add(AppStartedEvent()),
  ),

This generates an event right after Bloc is initialized.

A basically is a state machine. It does not do parallelism, that's not what it's built for. It's sequentially going from one state into another. In doing that, it can do things in parallel internally, but it cannot (or should not) take input in parallel.

If you want one event to execute multiple awaitable actions in parallel, you can do that:

@override
Stream<MyBlocState> mapEventToState(MyBlocEvent event) async* {
    if (event is CallTheAPIsEvent) {
        final results = await Future.wait([
           _repository.getAPI1(),
           _repository.getAPI2()
        ]);

        // do something with the results 

        yield ApisHaveBeenCalledState();
    }

    // more event handling
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM