Chromium Code Reviews| 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..97c48f3fb78a78b131c5487b1c8cb3da474d32be |
| --- /dev/null |
| +++ b/lib/src/async_thunk.dart |
| @@ -0,0 +1,46 @@ |
| +// 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/02 12:25:58
The "Thunk" name doesn't match what I normally thi
nweiz
2015/07/06 21:04:16
The idea was to evoke the lazy-evaluation language
Lasse Reichstein Nielsen
2015/07/07 09:32:40
I thought so, and it might be possible to put the
nweiz
2015/07/07 21:46:31
Changed to AsyncMemoizer.
|
| + /// 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. |
| + /// |
| + /// If [run] has already been called, this returns the original result. |
| + Future<T> run(fn()) { |
|
Lasse Reichstein Nielsen
2015/07/02 12:25:58
Do you actually expect the run function to be call
nweiz
2015/07/06 21:04:16
That would work well with slightly different langu
Lasse Reichstein Nielsen
2015/07/07 09:32:40
So you only expect the "run" function to be called
nweiz
2015/07/07 21:46:31
Done.
|
| + if (_future == null) _future = new Future.sync(fn); |
| + return _future; |
| + } |
| +} |