Skip to content

Instantly share code, notes, and snippets.

@Aidanvii7
Last active August 3, 2019 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aidanvii7/64b0863c694ea53c4ce6a03c31ebf256 to your computer and use it in GitHub Desktop.
Save Aidanvii7/64b0863c694ea53c4ce6a03c31ebf256 to your computer and use it in GitHub Desktop.
Example of how to use Dart's Completer
typedef CompleterBlock<T> = void Function(Completer<T> completer);
Future<T> completer<T>(final CompleterBlock<T> block) {
assert(block != null);
final completer = Completer<T>();
block(completer);
return completer.future;
}
import 'async_utils.dart';
import 'third_party_api.dart';
Future<void> doSomething() async {
//bridge the gap using a Completer
return completer((completer) {
ThirdPartyApi().doSomethingThen(() {
// the returned Future from doSomething will complete here when when calling completer.complete()
completer.complete();
});
});
}
class ThirdPartyApi {
// lets say the third party API doesn't return a Future and instead
// takes a function that is run asynchronously
void doSomethingThen(final Function() block) {
Future.microtask(_longRunningTask).then((_) => block());
}
Future<void> _longRunningTask() {
//TODO imagine long running op here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment