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 test.util.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 class AsyncThunk<T> { | |
16 /// The completer for the method's result. | |
17 /// | |
18 /// This will be `null` if [run] hasn't been called yet. | |
19 Completer<T> _completer; | |
20 | |
21 /// Whether [run] has been called yet. | |
22 bool get hasRun => _completer != null; | |
23 | |
24 /// Runs the method body, [fn], if it hasn't been run before. | |
25 /// | |
26 /// If [fn] has been run before, returns the original result. | |
27 Future<T> run(fn()) { | |
28 if (_completer == null) { | |
29 _completer = new Completer.sync(); | |
30 new Future.sync(fn) | |
31 .then(_completer.complete) | |
32 .catchError(_completer.completeError); | |
33 } | |
34 | |
35 return _completer.future; | |
36 } | |
37 } | |
OLD | NEW |