Last active
August 3, 2019 15:24
-
-
Save Aidanvii7/64b0863c694ea53c4ce6a03c31ebf256 to your computer and use it in GitHub Desktop.
Example of how to use Dart's Completer
This file contains hidden or 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
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; | |
} |
This file contains hidden or 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 '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(); | |
}); | |
}); | |
} |
This file contains hidden or 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
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