zackattack
zackattack

Reputation: 239

How to await call to a Web service and deliver answer to multiple source in Flutter

I have a function that fetch data from a database and if there is no data it will call a Web Service , put the answer in the databse and return the answer.

In order to avoid multiple call to the Web Service I want if there is multiple call to the function while a call to the Web Service is still running, every call after the first one wait for the answer of the first call without calling the Web Service.

How can I achieve this ?

Sample of the code I have :

Future<String> function() async {
    String data = await database.getData();
    if (data == null) {
        data = await callWebService();
        await database.setData(data);
    }
    return data
}

If this matter, I use Chopper for the Web service call, and Mobx to manage the state of my app.

Upvotes: 1

Views: 127

Answers (1)

Yauhen Sampir
Yauhen Sampir

Reputation: 2104

You can use completer to achieve what you want Check the sample code below.

class TestService {
  Completer<String> _completer;

  Future<String> function() async {
    if (_completer == null) {
      _completer = Completer<String>();
    } else {
      return _completer.future;
    }

    String data = await database.getData();
    if (data == null) {
      data = await callWebService();
      await database.setData(data);
    }
    _completer.complete(data);
    _completer = null;
    return data;
  }
}

Upvotes: 2

Related Questions