Created
March 4, 2021 03:14
-
-
Save tcd93/d7d0c222009ef6b3b118d486368303ce to your computer and use it in GitHub Desktop.
Dart Completer sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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