fetchCepFromServices function

Future<Cep> fetchCepFromServices(
  1. String cepWithLeftPad
)

Implementation

Future<Cep> fetchCepFromServices(String cepWithLeftPad) {
  final completer = Completer<Cep>();

  final errors = <Error>[];

  final onValue = (Cep value) {
    if (!completer.isCompleted) completer.complete(value);
  };

  final futures = [
    fetchCorreiosService(cepWithLeftPad),
    fetchViaCepService(cepWithLeftPad)
  ];

  final onError = (error, StackTrace stack) {
    errors.add(error);

    if (!completer.isCompleted && futures.length == errors.length) {
      completer.completeError(error, stack);
    }
  };

  for (var future in futures) {
    future.then(onValue, onError: onError);
  }

  return completer.future;
}