Skip to content

Instantly share code, notes, and snippets.

@tcd93
Created March 4, 2021 03:14
Show Gist options
  • Save tcd93/d7d0c222009ef6b3b118d486368303ce to your computer and use it in GitHub Desktop.
Save tcd93/d7d0c222009ef6b3b118d486368303ce to your computer and use it in GitHub Desktop.
Dart Completer sample
import 'dart:async';
import 'dart:math';
class API {
void startMethod() {
Timer(Duration(seconds: 2), onMethodDone);
}
bool onMethodDone() {
final randomBool = Random().nextBool();
print('after 2 seconds, we have decided to ${randomBool ? "succeed" : "fail"}');
return randomBool;
}
}
class APIAsync extends API {
final Completer completer;
APIAsync(this.completer) : super() {
super.startMethod();
}
@override
bool onMethodDone() {
final result = super.onMethodDone();
result ? completer.complete(result) : completer.completeError('the API call failed');
return result;
}
}
void main() {
final _completer = Completer();
APIAsync(_completer);
_completer.future
//.then is called on `completer.complete()`
.then((value) => print('API completed: $value'))
//.onError is called on `completer.completeError()`
.onError((error, _) => print('API failed with error: $error'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment