Skip to content

Commit

Permalink
implementing future success
Browse files Browse the repository at this point in the history
  • Loading branch information
Leocardoso94 committed Oct 13, 2019
1 parent e68b407 commit 158ef11
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions lib/cep_future.dart
@@ -1,22 +1,49 @@
library cep_future;

import 'dart:async';

import 'package:cep_future/error.dart';
import 'package:cep_future/models/cep.dart';
import 'package:cep_future/services/correios.dart';
import 'package:cep_future/services/via_cep.dart';

const CEP_SIZE = 8;

Future<Cep> fetchCepFromServices(String cepWithLeftPad) => Future.any([
fetchViaCepService(cepWithLeftPad),
fetchCorreiosService(cepWithLeftPad),
]);
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;
}

void throwApplicationError(Object e) {
throw e;
}

void handleServicesError(Object aggregatedErrors) {
print(aggregatedErrors.runtimeType);
if (aggregatedErrors.runtimeType == ServiceError) {
throw SimpleError('Todos os serviços de CEP retornaram erro.');
}
Expand Down

0 comments on commit 158ef11

Please sign in to comment.