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/01 05:23:18
This can all just be:
class AsyncThunk<T> {
nweiz
2015/07/01 19:07:23
Done.
| |
31 /// The completer for the method's result. | |
32 /// | |
33 /// This will be `null` if [run] hasn't been called yet. | |
34 Completer<T> _completer; | |
35 | |
36 /// Whether [run] has been called yet. | |
37 bool get hasRun => _completer != 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()) { | |
43 if (_completer == null) { | |
44 _completer = new Completer.sync(); | |
45 new Future.sync(fn) | |
46 .then(_completer.complete) | |
47 .catchError(_completer.completeError); | |
48 } | |
49 | |
50 return _completer.future; | |
51 } | |
52 } | |
OLD | NEW |