Chromium Code Reviews| 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 library async.async_memoizer; | 5 library async.async_memoizer; |
| 6 | 6 |
| 7 import 'dart:async'; | 7 import 'dart:async'; |
| 8 | 8 |
| 9 /// A class for running an asynchronous function exactly once and caching its | 9 /// A class for running an asynchronous function exactly once and caching its |
| 10 /// result. | 10 /// result. |
| (...skipping 13 matching lines...) Expand all Loading... | |
| 24 /// final _closeMemo = new AsyncMemoizer(); | 24 /// final _closeMemo = new AsyncMemoizer(); |
| 25 /// | 25 /// |
| 26 /// Future close() => _closeMemo.runOnce(() { | 26 /// Future close() => _closeMemo.runOnce(() { |
| 27 /// // ... | 27 /// // ... |
| 28 /// }); | 28 /// }); |
| 29 /// } | 29 /// } |
| 30 /// ``` | 30 /// ``` |
| 31 class AsyncMemoizer<T> { | 31 class AsyncMemoizer<T> { |
| 32 /// The future containing the method's result. | 32 /// The future containing the method's result. |
| 33 /// | 33 /// |
| 34 /// This will be `null` if [run] hasn't been called yet. | 34 /// This can be accessed at any time, and will fire once [runOnce] is called. |
| 35 Future<T> _future; | 35 Future<T> get future => _completer.future; |
| 36 final _completer = new Completer(); | |
|
kevmoo
2015/09/03 11:58:33
Completer<T>
| |
| 36 | 37 |
| 37 /// Whether [run] has been called yet. | 38 /// Whether [run] has been called yet. |
| 38 bool get hasRun => _future != null; | 39 bool get hasRun => _completer.isCompleted; |
| 39 | 40 |
| 40 /// Runs the function, [computation], if it hasn't been run before. | 41 /// Runs the function, [computation], if it hasn't been run before. |
| 41 /// | 42 /// |
| 42 /// If [run] has already been called, this returns the original result. | 43 /// If [run] has already been called, this returns the original result. |
| 43 Future<T> runOnce(computation()) { | 44 Future<T> runOnce(computation()) { |
| 44 if (_future == null) _future = new Future.sync(computation); | 45 if (!hasRun) _completer.complete(new Future.sync(computation)); |
|
kevmoo
2015/09/03 11:58:33
new Future<T> ?
| |
| 45 return _future; | 46 return future; |
| 46 } | 47 } |
| 47 } | 48 } |
| OLD | NEW |