Azael
Azael

Reputation: 654

Dart: Use Futures to asynchronously fill a static var

I have defined a static var as Map for all instances of my element. If it contains a specific key, it should use the value. If the key is not contains the instance should get the data with a request and save it in the static map, so other instances could use it.

static var data = new Map();

func() {
  if (Elem.data.containsKey(['key']) {
    list = Elem.data['key'];
  }
  else {
    Helper.getData().then((requestedData) {
      list = requestedData;
      Elem.data.addAll({ 'key' : requestedData });
  }
}

The Problem is that all my instances go into the else, since the key is not contained in the Map at the moment the other instances are at the if. So i need them to wait, until the Data is in the Map.

Upvotes: 4

Views: 135

Answers (2)

Florian Loitsch
Florian Loitsch

Reputation: 8128

In response to Günter Zöchbauer. I generally avoid using Completers directly:

static var data = new Map();
static Future _pendingFuture;

Future func() {
  if (_pendingFuture == null) {
    _pendingFuture = Helper.getData().then((requestedData) {
      list = requestedData;
      Elem.data.addAll({ 'key' : requestedData });
    });
  }
  return _pendingFuture;
}

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657496

static var data = new Map();
static Completer _dataCompleter;

Future<bool> func() {
  if(_dataCompleter == null) {
    _dataCompleter = new Completer();
    Helper.getData().then((requestedData) {
      list = requestedData;
      Elem.data.addAll({ 'key' : requestedData });
      _dataCompleter.complete(true);
    })
  } 
  if(_dataCompleter.isCompleted) {
    return new Future.value(true);
  } 
  return _dataCompleter.future;
}

and call it like

func().then((success) => /* continue here when `key` in `data` has a value.

Upvotes: 4

Related Questions