| OLD | NEW |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | 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 | 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. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 import 'dart:async'; | 5 import 'dart:async'; |
| 6 | 6 |
| 7 /// A class for running an asynchronous function exactly once and caching its | 7 /// A class for running an asynchronous function exactly once and caching its |
| 8 /// result. | 8 /// result. |
| 9 /// | 9 /// |
| 10 /// An `AsyncMemoizer` is used when some function may be run multiple times in | 10 /// An `AsyncMemoizer` is used when some function may be run multiple times in |
| (...skipping 13 matching lines...) Expand all Loading... |
| 24 /// Future close() => _closeMemo.runOnce(() { | 24 /// Future close() => _closeMemo.runOnce(() { |
| 25 /// // ... | 25 /// // ... |
| 26 /// }); | 26 /// }); |
| 27 /// } | 27 /// } |
| 28 /// ``` | 28 /// ``` |
| 29 class AsyncMemoizer<T> { | 29 class AsyncMemoizer<T> { |
| 30 /// The future containing the method's result. | 30 /// The future containing the method's result. |
| 31 /// | 31 /// |
| 32 /// This can be accessed at any time, and will fire once [runOnce] is called. | 32 /// This can be accessed at any time, and will fire once [runOnce] is called. |
| 33 Future<T> get future => _completer.future; | 33 Future<T> get future => _completer.future; |
| 34 final _completer = new Completer(); | 34 final _completer = new Completer<T>(); |
| 35 | 35 |
| 36 /// Whether [runOnce] has been called yet. | 36 /// Whether [runOnce] has been called yet. |
| 37 bool get hasRun => _completer.isCompleted; | 37 bool get hasRun => _completer.isCompleted; |
| 38 | 38 |
| 39 /// Runs the function, [computation], if it hasn't been run before. | 39 /// Runs the function, [computation], if it hasn't been run before. |
| 40 /// | 40 /// |
| 41 /// If [runOnce] has already been called, this returns the original result. | 41 /// If [runOnce] has already been called, this returns the original result. |
| 42 Future<T> runOnce(computation()) { | 42 Future<T> runOnce(computation()) { |
| 43 if (!hasRun) _completer.complete(new Future.sync(computation)); | 43 if (!hasRun) _completer.complete(new Future.sync(computation)); |
| 44 return future; | 44 return future; |
| 45 } | 45 } |
| 46 } | 46 } |
| OLD | NEW |