OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library async.async_memoizer; |
| 6 |
| 7 import 'dart:async'; |
| 8 |
| 9 /// A class for running an asynchronous function exactly once and caching its |
| 10 /// result. |
| 11 /// |
| 12 /// An `AsyncMemoizer` is used when some function may be run multiple times in |
| 13 /// order to get its result, but it only actually needs to be run once for its |
| 14 /// effect. To memoize the result of an async function, you can create a |
| 15 /// memoizer outside the function (for example as an instance field if you want |
| 16 /// to memoize the result of a method), and then wrap the function's body in a |
| 17 /// call to [runOnce]. |
| 18 /// |
| 19 /// This is useful for methods like `close()` and getters that need to do |
| 20 /// asynchronous work. For example: |
| 21 /// |
| 22 /// ```dart |
| 23 /// class SomeResource { |
| 24 /// final _closeMemo = new AsyncMemoizer(); |
| 25 /// |
| 26 /// Future close() => _closeMemo.runOnce(() { |
| 27 /// // ... |
| 28 /// }); |
| 29 /// } |
| 30 /// ``` |
| 31 class AsyncMemoizer<T> { |
| 32 /// The future containing the method's result. |
| 33 /// |
| 34 /// This will be `null` if [run] hasn't been called yet. |
| 35 Future<T> _future; |
| 36 |
| 37 /// Whether [run] has been called yet. |
| 38 bool get hasRun => _future != null; |
| 39 |
| 40 /// Runs the function, [computation], if it hasn't been run before. |
| 41 /// |
| 42 /// If [run] has already been called, this returns the original result. |
| 43 Future<T> runOnce(computation()) { |
| 44 if (_future == null) _future = new Future.sync(computation); |
| 45 return _future; |
| 46 } |
| 47 } |
OLD | NEW |