Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(559)

Unified Diff: lib/src/async_thunk.dart

Issue 1220963002: Add an AsyncThunk class. (Closed) Base URL: git@github.com:dart-lang/async.git@master
Patch Set: Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « lib/async.dart ('k') | pubspec.yaml » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: lib/src/async_thunk.dart
diff --git a/lib/src/async_thunk.dart b/lib/src/async_thunk.dart
new file mode 100644
index 0000000000000000000000000000000000000000..e3fb71829576bb526d3024d316b631f060b873cb
--- /dev/null
+++ b/lib/src/async_thunk.dart
@@ -0,0 +1,52 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library async.async_thunk;
+
+import 'dart:async';
+
+/// A class for running an asynchronous method body exactly once and caching its
+/// result.
+///
+/// This should be stored as an instance variable, and [run] should be called
+/// when the method is invoked with the uncached method body. The first time, it
+/// runs the body; after that, it returns the future from the first run.
+///
+/// This is useful for methods like `close()` and getters that need to do
+/// asynchronous work. For example:
+///
+/// ```dart
+/// class SomeResource {
+/// final _closeThunk = new AsyncThunk();
+///
+/// Future close() {
+/// return _closeThunk.run(() {
+/// // ...
+/// });
+/// }
+/// }
+/// ```
+class AsyncThunk<T> {
Lasse Reichstein Nielsen 2015/07/01 05:23:18 This can all just be: class AsyncThunk<T> {
nweiz 2015/07/01 19:07:23 Done.
+ /// The completer for the method's result.
+ ///
+ /// This will be `null` if [run] hasn't been called yet.
+ Completer<T> _completer;
+
+ /// Whether [run] has been called yet.
+ bool get hasRun => _completer != null;
+
+ /// Runs the method body, [fn], if it hasn't been run before.
+ ///
+ /// If [run] has already been called, this returns the original result.
+ Future<T> run(fn()) {
+ if (_completer == null) {
+ _completer = new Completer.sync();
+ new Future.sync(fn)
+ .then(_completer.complete)
+ .catchError(_completer.completeError);
+ }
+
+ return _completer.future;
+ }
+}
« no previous file with comments | « lib/async.dart ('k') | pubspec.yaml » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698