krishnakumarcn
krishnakumarcn

Reputation: 4199

Dart: How to create a future from multiple completers

I want to create a future from multiple completers in dart/flutter.

Future getAndWriteToDB(conversations){
    List<Completer> _completerList = List();

    for (var i = 0; i < conversations.length; i++) {
      final conversation = conversations[i];
      _completerList.add(Completer());
      SocketService()
          .listenForEvent('mylistenerkey')
          .then((data) {
         _messagesDao.insertMessages(messages).then((result) {
            if (result == false) {
              print("writing to db for message failed");
            } else {
              _completerList[i].complete(true);
            }
          });
        }
      });
    }


    return {{ wait for these completers complete event }}
}

Here my SocketService().listenForEvent gets called whenever that event is available. I want to write all of my conversations to database then once all those are completed get to know that state. So I need to wait for or create a future based on these list of completers. How can I achieve this?

Upvotes: 1

Views: 1129

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76283

You can use Future.wait:

return Future.wait(_completerList.map((e) => e.future));

Upvotes: 6

Related Questions