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

Unified Diff: lib/src/async_memoizer.dart

Issue 1220963002: Add an AsyncThunk class. (Closed) Base URL: git@github.com:dart-lang/async.git@master
Patch Set: Code review changes Created 5 years, 5 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
Index: lib/src/async_memoizer.dart
diff --git a/lib/src/async_memoizer.dart b/lib/src/async_memoizer.dart
new file mode 100644
index 0000000000000000000000000000000000000000..d464760296518a120ca068943f4ed0bb75988219
--- /dev/null
+++ b/lib/src/async_memoizer.dart
@@ -0,0 +1,45 @@
+// 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_memoizer;
+
+import 'dart:async';
+
+/// A class for running an asynchronous method body exactly once and caching its
Lasse Reichstein Nielsen 2015/07/08 07:37:34 method body -> function
nweiz 2015/07/09 00:45:13 Done.
+/// result.
+///
+/// This should be stored as an instance variable, and [runOnce] should be
Lasse Reichstein Nielsen 2015/07/08 07:37:34 Drop the usage of "this", or at least don't make i
nweiz 2015/07/09 00:45:13 Done.
+/// 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
Lasse Reichstein Nielsen 2015/07/08 07:37:34 Does DartDoc understand "```dart" now! If so, yey!
nweiz 2015/07/09 00:45:13 I think so? I'm not 100% sure, but I'll keep an ey
+/// class SomeResource {
+/// final _closeMemo = new AsyncMemoizer();
+///
+/// Future close() => _closeMemo.runOnce(() {
+/// // ...
+/// });
+/// }
+/// ```
+class AsyncMemoizer<T> {
+ /// The future containing the method's result.
+ ///
+ /// This will be `null` if [run] hasn't been called yet.
+ Future<T> _future;
+
+ /// Whether [run] has been called yet.
+ bool get hasRun => _future != null;
+
+ /// Runs the method body, [fn], if it hasn't been run before.
Lasse Reichstein Nielsen 2015/07/08 07:37:34 method body -> function.
nweiz 2015/07/09 00:45:13 Done.
+ ///
+ /// If [run] has already been called, this returns the original result.
+ Future<T> runOnce(fn()) {
Lasse Reichstein Nielsen 2015/07/08 07:37:34 Rename "fn" to "computation". This matches the arg
nweiz 2015/07/09 00:45:13 Done.
+ if (_future == null) _future = new Future.sync(fn);
+ return _future;
+ }
+}

Powered by Google App Engine
This is Rietveld 408576698