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; |
+ } |
+} |