Chromium Code Reviews| 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_thunk; | |
| 6 | |
| 7 import 'dart:async'; | |
| 8 | |
| 9 /// A class for running an asynchronous method body exactly once and caching its | |
| 10 /// result. | |
| 11 /// | |
| 12 /// This should be stored as an instance variable, and [run] should be called | |
| 13 /// when the method is invoked with the uncached method body. The first time, it | |
| 14 /// runs the body; after that, it returns the future from the first run. | |
| 15 /// | |
| 16 /// This is useful for methods like `close()` and getters that need to do | |
| 17 /// asynchronous work. For example: | |
| 18 /// | |
| 19 /// ```dart | |
| 20 /// class SomeResource { | |
| 21 /// final _closeThunk = new AsyncThunk(); | |
| 22 /// | |
| 23 /// Future close() { | |
| 24 /// return _closeThunk.run(() { | |
| 25 /// // ... | |
| 26 /// }); | |
| 27 /// } | |
| 28 /// } | |
| 29 /// ``` | |
| 30 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.
| |
| 31 /// The future containing the method's result. | |
| 32 /// | |
| 33 /// This will be `null` if [run] hasn't been called yet. | |
| 34 Future<T> _future; | |
| 35 | |
| 36 /// Whether [run] has been called yet. | |
| 37 bool get hasRun => _future != null; | |
| 38 | |
| 39 /// Runs the method body, [fn], if it hasn't been run before. | |
| 40 /// | |
| 41 /// If [run] has already been called, this returns the original result. | |
| 42 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.
| |
| 43 if (_future == null) _future = new Future.sync(fn); | |
| 44 return _future; | |
| 45 } | |
| 46 } | |
| OLD | NEW |