Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(37)

Side by Side Diff: lib/src/async_thunk.dart

Issue 1220963002: Add an AsyncThunk class. (Closed) Base URL: git@github.com:dart-lang/async.git@master
Patch Set: Created 5 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « lib/async.dart ('k') | pubspec.yaml » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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 }
OLDNEW
« no previous file with comments | « lib/async.dart ('k') | pubspec.yaml » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698