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

Side by Side Diff: sdk/lib/async/future_impl.dart

Issue 637893002: Use a _FutureListener separate from the _Future to hold listeners. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Addressed comments. Created 6 years, 2 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 | Annotate | Revision Log
« no previous file with comments | « no previous file | sdk/lib/async/schedule_microtask.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2012, 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 part of dart.async; 5 part of dart.async;
6 6
7 /** The onValue and onError handlers return either a value or a future */ 7 /** The onValue and onError handlers return either a value or a future */
8 typedef dynamic _FutureOnValue<T>(T value); 8 typedef dynamic _FutureOnValue<T>(T value);
9 /** Test used by [Future.catchError] to handle skip some errors. */ 9 /** Test used by [Future.catchError] to handle skip some errors. */
10 typedef bool _FutureErrorTest(var error); 10 typedef bool _FutureErrorTest(var error);
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
50 void complete([value]) { 50 void complete([value]) {
51 if (!future._mayComplete) throw new StateError("Future already completed"); 51 if (!future._mayComplete) throw new StateError("Future already completed");
52 future._complete(value); 52 future._complete(value);
53 } 53 }
54 54
55 void _completeError(Object error, StackTrace stackTrace) { 55 void _completeError(Object error, StackTrace stackTrace) {
56 future._completeError(error, stackTrace); 56 future._completeError(error, stackTrace);
57 } 57 }
58 } 58 }
59 59
60 class _FutureListener {
61 static const int MASK_VALUE = 1;
62 static const int MASK_ERROR = 2;
63 static const int MASK_TEST_ERROR = 4;
64 static const int MASK_WHENCOMPLETE = 8;
65 static const int STATE_CHAIN = 0;
66 static const int STATE_THEN = MASK_VALUE;
67 static const int STATE_THEN_ONERROR = MASK_VALUE | MASK_ERROR;
68 static const int STATE_CATCHERROR = MASK_ERROR;
69 static const int STATE_CATCHERROR_TEST = MASK_ERROR | MASK_TEST_ERROR;
70 static const int STATE_WHENCOMPLETE = MASK_WHENCOMPLETE;
71 // Listeners on the same future are linked through this link.
72 _FutureListener _nextListener = null;
73 // The future to complete when this listener is activated.
74 final _Future result;
75 // Which fields means what.
76 final int state;
77 // Used for then/whenDone callback and error test
78 final Function callback;
79 // Used for error callbacks.
80 final Function errorCallback;
81
82 _FutureListener.then(this.result,
83 _FutureOnValue onValue, Function errorCallback)
84 : callback = onValue,
85 errorCallback = errorCallback,
86 state = (errorCallback == null) ? STATE_THEN : STATE_THEN_ONERROR;
87
88 _FutureListener.catchError(this.result,
89 this.errorCallback, _FutureErrorTest test)
90 : callback = test,
91 state = (test == null) ? STATE_CATCHERROR : STATE_CATCHERROR_TEST;
92
93 _FutureListener.whenComplete(this.result, _FutureAction onComplete)
94 : callback = onComplete,
95 errorCallback = null,
96 state = STATE_WHENCOMPLETE;
97
98 _FutureListener.chain(this.result)
99 : callback = null,
100 errorCallback = null,
101 state = STATE_CHAIN;
102
103 Zone get _zone => result._zone;
104
105 bool get handlesValue => (state & MASK_VALUE != 0);
106 bool get handlesError => (state & MASK_ERROR != 0);
107 bool get hasErrorTest => (state == STATE_CATCHERROR_TEST);
108 bool get handlesComplete => (state == STATE_WHENCOMPLETE);
109
110 _FutureOnValue get _onValue {
111 assert(handlesValue);
112 return callback;
113 }
114 Function get _onError => errorCallback;
115 _FutureErrorTest get _errorTest {
116 assert(hasErrorTest);
117 return callback;
118 }
119 _FutureAction get _whenCompleteAction {
120 assert(handlesComplete);
121 return callback;
122 }
123 }
124
60 class _Future<T> implements Future<T> { 125 class _Future<T> implements Future<T> {
61 // State of the future. The state determines the interpretation of the
62 // [resultOrListeners] field.
63 // TODO(lrn): rename field since it can also contain a chained future.
64
65 /// Initial state, waiting for a result. In this state, the 126 /// Initial state, waiting for a result. In this state, the
66 /// [resultOrListeners] field holds a single-linked list of 127 /// [resultOrListeners] field holds a single-linked list of
67 /// [FutureListener] listeners. 128 /// [_FutureListener] listeners.
68 static const int _INCOMPLETE = 0; 129 static const int _INCOMPLETE = 0;
69 /// Pending completion. Set when completed using [_asyncComplete] or 130 /// Pending completion. Set when completed using [_asyncComplete] or
70 /// [_asyncCompleteError]. It is an error to try to complete it again. 131 /// [_asyncCompleteError]. It is an error to try to complete it again.
132 /// [resultOrListeners] holds listeners.
71 static const int _PENDING_COMPLETE = 1; 133 static const int _PENDING_COMPLETE = 1;
72 /// The future has been chained to another future. The result of that 134 /// The future has been chained to another future. The result of that
73 /// other future becomes the result of this future as well. 135 /// other future becomes the result of this future as well.
74 /// In this state, no callback should be executed anymore.
75 // TODO(floitsch): we don't really need a special "_CHAINED" state. We could 136 // TODO(floitsch): we don't really need a special "_CHAINED" state. We could
76 // just use the PENDING_COMPLETE state instead. 137 // just use the PENDING_COMPLETE state instead.
77 static const int _CHAINED = 2; 138 static const int _CHAINED = 2;
78 /// The future has been completed with a value result. 139 /// The future has been completed with a value result.
79 static const int _VALUE = 4; 140 static const int _VALUE = 4;
80 /// The future has been completed with an error result. 141 /// The future has been completed with an error result.
81 static const int _ERROR = 8; 142 static const int _ERROR = 8;
82 143
83 /** Whether the future is complete, and as what. */ 144 /** Whether the future is complete, and as what. */
84 int _state = _INCOMPLETE; 145 int _state = _INCOMPLETE;
85 146
86 final Zone _zone; 147 /**
87 148 * Zone that the future was completed from.
88 bool get _mayComplete => _state == _INCOMPLETE; 149 * This is the zone that an error result belongs to.
89 bool get _isChained => _state == _CHAINED; 150 *
90 bool get _isComplete => _state >= _VALUE; 151 * Until the future is completed, the field may hold the zone that
91 bool get _hasValue => _state == _VALUE; 152 * listener callbacks used to create this future should be run in.
92 bool get _hasError => _state == _ERROR; 153 */
93 154 final Zone _zone = Zone.current;
94 set _isChained(bool value) {
95 if (value) {
96 assert(!_isComplete);
97 _state = _CHAINED;
98 } else {
99 assert(_isChained);
100 _state = _INCOMPLETE;
101 }
102 }
103 155
104 /** 156 /**
105 * Either the result, a list of listeners or another future. 157 * Either the result, a list of listeners or another future.
106 * 158 *
107 * The result of the future is either a value or an error. 159 * The result of the future is either a value or an error.
108 * A result is only stored when the future has completed. 160 * A result is only stored when the future has completed.
109 * 161 *
110 * The listeners is an internally linked list of [_FutureListener]s. 162 * The listeners is an internally linked list of [_FutureListener]s.
111 * Listeners are only remembered while the future is not yet complete, 163 * Listeners are only remembered while the future is not yet complete,
112 * and it is not chained to another future. 164 * and it is not chained to another future.
113 * 165 *
114 * The future is another future that his future is chained to. This future 166 * The future is another future that his future is chained to. This future
115 * is waiting for the other future to complete, and when it does, this future 167 * is waiting for the other future to complete, and when it does, this future
116 * will complete with the same result. 168 * will complete with the same result.
117 * All listeners are forwarded to the other future. 169 * All listeners are forwarded to the other future.
118 * 170 *
119 * The cases are disjoint (incomplete and unchained, incomplete and 171 * The cases are disjoint - incomplete and unchained ([_INCOMPLETE]),
120 * chained, or completed with value or error), so the field only needs to hold 172 * incomplete and chained ([_CHAINED]), or completed with value or error
173 * ([_VALUE] or [_ERROR]) - so the field only needs to hold
121 * one value at a time. 174 * one value at a time.
122 */ 175 */
123 var _resultOrListeners; 176 var _resultOrListeners;
124 177
125 /** 178 _Future();
126 * A [_Future] implements a linked list. If a future has more than one
127 * listener the [_nextListener] field of the first listener points to the
128 * remaining listeners.
129 */
130 // TODO(floitsch): since single listeners are the common case we should
131 // use a bit to indicate that the _resultOrListeners contains a container.
132 _Future _nextListener;
133
134 // TODO(floitsch): we only need two closure fields to store the callbacks.
135 // If we store the type of a closure in the state field (where there are
136 // still bits left), we can just store two closures instead of using 4
137 // fields of which 2 are always null.
138 _FutureOnValue _onValueCallback;
139 _FutureErrorTest _errorTestCallback;
140 Function _onErrorCallback;
141 _FutureAction _whenCompleteActionCallback;
142
143 _FutureOnValue get _onValue => _isChained ? null : _onValueCallback;
144 _FutureErrorTest get _errorTest => _isChained ? null : _errorTestCallback;
145 Function get _onError => _isChained ? null : _onErrorCallback;
146 _FutureAction get _whenCompleteAction
147 => _isChained ? null : _whenCompleteActionCallback;
148
149 _Future()
150 : _zone = Zone.current,
151 _onValueCallback = null, _errorTestCallback = null,
152 _onErrorCallback = null, _whenCompleteActionCallback = null;
153 179
154 /// Valid types for value: `T` or `Future<T>`. 180 /// Valid types for value: `T` or `Future<T>`.
155 _Future.immediate(value) 181 _Future.immediate(value) {
156 : _zone = Zone.current,
157 _onValueCallback = null, _errorTestCallback = null,
158 _onErrorCallback = null, _whenCompleteActionCallback = null {
159 _asyncComplete(value); 182 _asyncComplete(value);
160 } 183 }
161 184
162 _Future.immediateError(var error, [StackTrace stackTrace]) 185 _Future.immediateError(var error, [StackTrace stackTrace]) {
163 : _zone = Zone.current,
164 _onValueCallback = null, _errorTestCallback = null,
165 _onErrorCallback = null, _whenCompleteActionCallback = null {
166 _asyncCompleteError(error, stackTrace); 186 _asyncCompleteError(error, stackTrace);
167 } 187 }
168 188
169 _Future._then(onValueCallback(value), Function onErrorCallback) 189 bool get _mayComplete => _state == _INCOMPLETE;
170 : _zone = Zone.current, 190 bool get _isChained => _state == _CHAINED;
171 _onValueCallback = Zone.current.registerUnaryCallback(onValueCallback), 191 bool get _isComplete => _state >= _VALUE;
172 _onErrorCallback = _registerErrorHandler(onErrorCallback, Zone.current), 192 bool get _hasValue => _state == _VALUE;
173 _errorTestCallback = null, 193 bool get _hasError => _state == _ERROR;
174 _whenCompleteActionCallback = null;
175 194
176 _Future._catchError(Function onErrorCallback, bool errorTestCallback(e)) 195 set _isChained(bool value) {
177 : _zone = Zone.current, 196 if (value) {
178 _onErrorCallback = _registerErrorHandler(onErrorCallback, Zone.current), 197 assert(!_isComplete);
179 _errorTestCallback = 198 _state = _CHAINED;
180 Zone.current.registerUnaryCallback(errorTestCallback), 199 } else {
181 _onValueCallback = null, 200 assert(_isChained);
182 _whenCompleteActionCallback = null; 201 _state = _INCOMPLETE;
183 202 }
184 _Future._whenComplete(whenCompleteActionCallback()) 203 }
185 : _zone = Zone.current,
186 _whenCompleteActionCallback =
187 Zone.current.registerCallback(whenCompleteActionCallback),
188 _onValueCallback = null,
189 _errorTestCallback = null,
190 _onErrorCallback = null;
191 204
192 Future then(f(T value), { Function onError }) { 205 Future then(f(T value), { Function onError }) {
193 _Future result; 206 _Future result = new _Future();
194 result = new _Future._then(f, onError); 207 if (!identical(result._zone, _ROOT_ZONE)) {
195 _addListener(result); 208 f = result._zone.registerUnaryCallback(f);
209 if (onError != null) {
210 onError = _registerErrorHandler(onError, result._zone);
211 }
212 }
213 _addListener(new _FutureListener.then(result, f, onError));
196 return result; 214 return result;
197 } 215 }
198 216
199 Future catchError(Function onError, { bool test(error) }) { 217 Future catchError(Function onError, { bool test(error) }) {
200 _Future result = new _Future._catchError(onError, test); 218 _Future result = new _Future();
201 _addListener(result); 219 if (!identical(result._zone, _ROOT_ZONE)) {
220 onError = _registerErrorHandler(onError, result._zone);
221 if (test != null) test = result._zone.registerUnaryCallback(test);
222 }
223 _addListener(new _FutureListener.catchError(result, onError, test));
202 return result; 224 return result;
203 } 225 }
204 226
205 Future<T> whenComplete(action()) { 227 Future<T> whenComplete(action()) {
206 _Future result = new _Future<T>._whenComplete(action); 228 _Future result = new _Future<T>();
207 _addListener(result); 229 if (!identical(result._zone, _ROOT_ZONE)) {
230 action = result._zone.registerCallback(action);
231 }
232 _addListener(new _FutureListener.whenComplete(result, action));
208 return result; 233 return result;
209 } 234 }
210 235
211 Stream<T> asStream() => new Stream.fromFuture(this); 236 Stream<T> asStream() => new Stream.fromFuture(this);
212 237
213 void _markPendingCompletion() { 238 void _markPendingCompletion() {
214 if (!_mayComplete) throw new StateError("Future already completed"); 239 if (!_mayComplete) throw new StateError("Future already completed");
215 _state = _PENDING_COMPLETE; 240 _state = _PENDING_COMPLETE;
216 } 241 }
217 242
218 T get _value { 243 T get _value {
219 assert(_isComplete && _hasValue); 244 assert(_isComplete && _hasValue);
220 return _resultOrListeners; 245 return _resultOrListeners;
221 } 246 }
222 247
223 AsyncError get _error { 248 AsyncError get _error {
224 assert(_isComplete && _hasError); 249 assert(_isComplete && _hasError);
225 return _resultOrListeners; 250 return _resultOrListeners;
226 } 251 }
227 252
228 void _setValue(T value) { 253 void _setValue(T value) {
229 assert(!_isComplete); // But may have a completion pending. 254 assert(!_isComplete); // But may have a completion pending.
230 _state = _VALUE; 255 _state = _VALUE;
231 _resultOrListeners = value; 256 _resultOrListeners = value;
232 } 257 }
233 258
234 void _setError(Object error, StackTrace stackTrace) { 259 void _setErrorObject(AsyncError error) {
235 assert(!_isComplete); // But may have a completion pending. 260 assert(!_isComplete); // But may have a completion pending.
236 _state = _ERROR; 261 _state = _ERROR;
237 _resultOrListeners = new AsyncError(error, stackTrace); 262 _resultOrListeners = error;
238 } 263 }
239 264
240 void _addListener(_Future listener) { 265 void _setError(Object error, StackTrace stackTrace) {
266 _setErrorObject(new AsyncError(error, stackTrace));
267 }
268
269 void _addListener(_FutureListener listener) {
241 assert(listener._nextListener == null); 270 assert(listener._nextListener == null);
242 if (_isComplete) { 271 if (_isComplete) {
243 // Handle late listeners asynchronously. 272 // Handle late listeners asynchronously.
244 _zone.scheduleMicrotask(() { 273 _zone.scheduleMicrotask(() {
245 _propagateToListeners(this, listener); 274 _propagateToListeners(this, listener);
246 }); 275 });
247 } else { 276 } else {
248 listener._nextListener = _resultOrListeners; 277 listener._nextListener = _resultOrListeners;
249 _resultOrListeners = listener; 278 _resultOrListeners = listener;
250 } 279 }
251 } 280 }
252 281
253 _Future _removeListeners() { 282 _FutureListener _removeListeners() {
254 // Reverse listeners before returning them, so the resulting list is in 283 // Reverse listeners before returning them, so the resulting list is in
255 // subscription order. 284 // subscription order.
256 assert(!_isComplete); 285 assert(!_isComplete);
257 _Future current = _resultOrListeners; 286 _FutureListener current = _resultOrListeners;
258 _resultOrListeners = null; 287 _resultOrListeners = null;
259 _Future prev = null; 288 _FutureListener prev = null;
260 while (current != null) { 289 while (current != null) {
261 _Future next = current._nextListener; 290 _FutureListener next = current._nextListener;
262 current._nextListener = prev; 291 current._nextListener = prev;
263 prev = current; 292 prev = current;
264 current = next; 293 current = next;
265 } 294 }
266 return prev; 295 return prev;
267 } 296 }
268 297
269 // Take the value (when completed) of source and complete target with that 298 // Take the value (when completed) of source and complete target with that
270 // value (or error). This function can chain all Futures, but is slower 299 // value (or error). This function can chain all Futures, but is slower
271 // for _Future than _chainCoreFuture - Use _chainCoreFuture in that case. 300 // for _Future than _chainCoreFuture - Use _chainCoreFuture in that case.
(...skipping 18 matching lines...) Expand all
290 } 319 }
291 320
292 // Take the value (when completed) of source and complete target with that 321 // Take the value (when completed) of source and complete target with that
293 // value (or error). This function expects that source is a _Future. 322 // value (or error). This function expects that source is a _Future.
294 static void _chainCoreFuture(_Future source, _Future target) { 323 static void _chainCoreFuture(_Future source, _Future target) {
295 assert(!target._isComplete); 324 assert(!target._isComplete);
296 assert(source is _Future); 325 assert(source is _Future);
297 326
298 // Mark the target as chained (and as such half-completed). 327 // Mark the target as chained (and as such half-completed).
299 target._isChained = true; 328 target._isChained = true;
300 _Future internalFuture = source; 329 _FutureListener listener = new _FutureListener.chain(target);
301 if (internalFuture._isComplete) { 330 if (source._isComplete) {
302 _propagateToListeners(internalFuture, target); 331 _propagateToListeners(source, listener);
303 } else { 332 } else {
304 internalFuture._addListener(target); 333 source._addListener(listener);
305 } 334 }
306 } 335 }
307 336
308 void _complete(value) { 337 void _complete(value) {
309 assert(!_isComplete); 338 assert(!_isComplete);
310 assert(_onValue == null);
311 assert(_onError == null);
312 assert(_whenCompleteAction == null);
313 assert(_errorTest == null);
314
315 if (value is Future) { 339 if (value is Future) {
316 if (value is _Future) { 340 if (value is _Future) {
317 _chainCoreFuture(value, this); 341 _chainCoreFuture(value, this);
318 } else { 342 } else {
319 _chainForeignFuture(value, this); 343 _chainForeignFuture(value, this);
320 } 344 }
321 } else { 345 } else {
322 _Future listeners = _removeListeners(); 346 _FutureListener listeners = _removeListeners();
323 _setValue(value); 347 _setValue(value);
324 _propagateToListeners(this, listeners); 348 _propagateToListeners(this, listeners);
325 } 349 }
326 } 350 }
327 351
328 void _completeWithValue(value) { 352 void _completeWithValue(value) {
329 assert(!_isComplete); 353 assert(!_isComplete);
330 assert(_onValue == null);
331 assert(_onError == null);
332 assert(_whenCompleteAction == null);
333 assert(_errorTest == null);
334 assert(value is! Future); 354 assert(value is! Future);
335 355
336 _Future listeners = _removeListeners(); 356 _FutureListener listeners = _removeListeners();
337 _setValue(value); 357 _setValue(value);
338 _propagateToListeners(this, listeners); 358 _propagateToListeners(this, listeners);
339 } 359 }
340 360
341 void _completeError(error, [StackTrace stackTrace]) { 361 void _completeError(error, [StackTrace stackTrace]) {
342 assert(!_isComplete); 362 assert(!_isComplete);
343 assert(_onValue == null);
344 assert(_onError == null);
345 assert(_whenCompleteAction == null);
346 assert(_errorTest == null);
347 363
348 _Future listeners = _removeListeners(); 364 _FutureListener listeners = _removeListeners();
349 _setError(error, stackTrace); 365 _setError(error, stackTrace);
350 _propagateToListeners(this, listeners); 366 _propagateToListeners(this, listeners);
351 } 367 }
352 368
353 void _asyncComplete(value) { 369 void _asyncComplete(value) {
354 assert(!_isComplete); 370 assert(!_isComplete);
355 assert(_onValue == null);
356 assert(_onError == null);
357 assert(_whenCompleteAction == null);
358 assert(_errorTest == null);
359 // Two corner cases if the value is a future: 371 // Two corner cases if the value is a future:
360 // 1. the future is already completed and an error. 372 // 1. the future is already completed and an error.
361 // 2. the future is not yet completed but might become an error. 373 // 2. the future is not yet completed but might become an error.
362 // The first case means that we must not immediately complete the Future, 374 // The first case means that we must not immediately complete the Future,
363 // as our code would immediately start propagating the error without 375 // as our code would immediately start propagating the error without
364 // giving the time to install error-handlers. 376 // giving the time to install error-handlers.
365 // However the second case requires us to deal with the value immediately. 377 // However the second case requires us to deal with the value immediately.
366 // Otherwise the value could complete with an error and report an 378 // Otherwise the value could complete with an error and report an
367 // unhandled error, even though we know we are already going to listen to 379 // unhandled error, even though we know we are already going to listen to
368 // it. 380 // it.
(...skipping 27 matching lines...) Expand all
396 } 408 }
397 409
398 _markPendingCompletion(); 410 _markPendingCompletion();
399 _zone.scheduleMicrotask(() { 411 _zone.scheduleMicrotask(() {
400 _completeWithValue(value); 412 _completeWithValue(value);
401 }); 413 });
402 } 414 }
403 415
404 void _asyncCompleteError(error, StackTrace stackTrace) { 416 void _asyncCompleteError(error, StackTrace stackTrace) {
405 assert(!_isComplete); 417 assert(!_isComplete);
406 assert(_onValue == null);
407 assert(_onError == null);
408 assert(_whenCompleteAction == null);
409 assert(_errorTest == null);
410 418
411 _markPendingCompletion(); 419 _markPendingCompletion();
412 _zone.scheduleMicrotask(() { 420 _zone.scheduleMicrotask(() {
413 _completeError(error, stackTrace); 421 _completeError(error, stackTrace);
414 }); 422 });
415 } 423 }
416 424
417 /** 425 /**
418 * Propagates the value/error of [source] to its [listeners].
419 *
420 * Unlinks all listeners and propagates the source to each listener
421 * separately.
422 */
423 static void _propagateMultipleListeners(_Future source, _Future listeners) {
424 assert(listeners != null);
425 assert(listeners._nextListener != null);
426 do {
427 _Future listener = listeners;
428 listeners = listener._nextListener;
429 listener._nextListener = null;
430 _propagateToListeners(source, listener);
431 } while (listeners != null);
432 }
433
434 /**
435 * Propagates the value/error of [source] to its [listeners], executing the 426 * Propagates the value/error of [source] to its [listeners], executing the
436 * listeners' callbacks. 427 * listeners' callbacks.
437 *
438 * If [runCallback] is true (which should be the default) it executes
439 * the registered action of listeners. If it is `false` then the callback is
440 * skipped. This is used to complete futures with chained futures.
441 */ 428 */
442 static void _propagateToListeners(_Future source, _Future listeners) { 429 static void _propagateToListeners(_Future source, _FutureListener listeners) {
443 while (true) { 430 while (true) {
444 if (!source._isComplete) return; // Chained future. 431 assert(source._isComplete);
445 bool hasError = source._hasError; 432 bool hasError = source._hasError;
446 if (hasError && listeners == null) { 433 if (listeners == null) {
447 AsyncError asyncError = source._error; 434 if (hasError) {
448 source._zone.handleUncaughtError( 435 AsyncError asyncError = source._error;
449 asyncError.error, asyncError.stackTrace); 436 source._zone.handleUncaughtError(
437 asyncError.error, asyncError.stackTrace);
438 }
450 return; 439 return;
451 } 440 }
452 if (listeners == null) return; 441 // Usually futures only have one listener. If they have several, we
453 _Future listener = listeners; 442 // call handle them separately in recursive calls, continuing
454 if (listener._nextListener != null) { 443 // here only when there is only one listener left.
455 // Usually futures only have one listener. If they have several, we 444 while (listeners._nextListener != null) {
456 // handle them specially. 445 _FutureListener listener = listeners;
457 _propagateMultipleListeners(source, listeners); 446 listeners = listener._nextListener;
458 return; 447 listener._nextListener = null;
448 _propagateToListeners(source, listener);
459 } 449 }
450 _FutureListener listener = listeners;
460 // Do the actual propagation. 451 // Do the actual propagation.
461 // Set initial state of listenerHasValue and listenerValueOrError. These 452 // Set initial state of listenerHasValue and listenerValueOrError. These
462 // variables are updated, with the outcome of potential callbacks. 453 // variables are updated, with the outcome of potential callbacks.
463 bool listenerHasValue = true; 454 bool listenerHasValue = true;
464 final sourceValue = source._hasValue ? source._value : null; 455 final sourceValue = hasError ? null : source._value;
465 var listenerValueOrError = sourceValue; 456 var listenerValueOrError = sourceValue;
466 // Set to true if a whenComplete needs to wait for a future. 457 // Set to true if a whenComplete needs to wait for a future.
467 // The whenComplete action will resume the propagation by itself. 458 // The whenComplete action will resume the propagation by itself.
468 bool isPropagationAborted = false; 459 bool isPropagationAborted = false;
469 // TODO(floitsch): mark the listener as pending completion. Currently 460 // TODO(floitsch): mark the listener as pending completion. Currently
470 // we can't do this, since the markPendingCompletion verifies that 461 // we can't do this, since the markPendingCompletion verifies that
471 // the future is not already marked (or chained). 462 // the future is not already marked (or chained).
472 // Only if we either have an error or callbacks, go into this, somewhat 463 // Only if we either have an error or callbacks, go into this, somewhat
473 // expensive, branch. Here we'll enter/leave the zone. Many futures 464 // expensive, branch. Here we'll enter/leave the zone. Many futures
474 // doesn't have callbacks, so this is a significant optimization. 465 // doesn't have callbacks, so this is a significant optimization.
475 if (hasError || 466 if (hasError || (listener.handlesValue || listener.handlesComplete)) {
476 listener._onValue != null ||
477 listener._whenCompleteAction != null) {
478 Zone zone = listener._zone; 467 Zone zone = listener._zone;
479 if (hasError && !source._zone.inSameErrorZone(zone)) { 468 if (hasError && !source._zone.inSameErrorZone(zone)) {
480 // Don't cross zone boundaries with errors. 469 // Don't cross zone boundaries with errors.
481 AsyncError asyncError = source._error; 470 AsyncError asyncError = source._error;
482 source._zone.handleUncaughtError( 471 source._zone.handleUncaughtError(
483 asyncError.error, asyncError.stackTrace); 472 asyncError.error, asyncError.stackTrace);
484 return; 473 return;
485 } 474 }
486 475
487 Zone oldZone; 476 Zone oldZone;
488 if (!identical(Zone.current, zone)) { 477 if (!identical(Zone.current, zone)) {
489 // Change zone if it's not current. 478 // Change zone if it's not current.
490 oldZone = Zone._enter(zone); 479 oldZone = Zone._enter(zone);
491 } 480 }
492 481
493 bool handleValueCallback() { 482 bool handleValueCallback() {
494 try { 483 try {
495 listenerValueOrError = zone.runUnary(listener._onValue, 484 listenerValueOrError = zone.runUnary(listener._onValue,
496 sourceValue); 485 sourceValue);
497 return true; 486 return true;
498 } catch (e, s) { 487 } catch (e, s) {
499 listenerValueOrError = new AsyncError(e, s); 488 listenerValueOrError = new AsyncError(e, s);
500 return false; 489 return false;
501 } 490 }
502 } 491 }
503 492
504 void handleError() { 493 void handleError() {
505 AsyncError asyncError = source._error; 494 AsyncError asyncError = source._error;
506 _FutureErrorTest test = listener._errorTest;
507 bool matchesTest = true; 495 bool matchesTest = true;
508 if (test != null) { 496 if (listener.hasErrorTest) {
497 _FutureErrorTest test = listener._errorTest;
509 try { 498 try {
510 matchesTest = zone.runUnary(test, asyncError.error); 499 matchesTest = zone.runUnary(test, asyncError.error);
511 } catch (e, s) { 500 } catch (e, s) {
512 // TODO(ajohnsen): Should we suport rethrow for test throws?
513 listenerValueOrError = identical(asyncError.error, e) ? 501 listenerValueOrError = identical(asyncError.error, e) ?
514 asyncError : new AsyncError(e, s); 502 asyncError : new AsyncError(e, s);
515 listenerHasValue = false; 503 listenerHasValue = false;
516 return; 504 return;
517 } 505 }
518 } 506 }
519 Function errorCallback = listener._onError; 507 Function errorCallback = listener._onError;
520 if (matchesTest && errorCallback != null) { 508 if (matchesTest && errorCallback != null) {
521 try { 509 try {
522 if (errorCallback is ZoneBinaryCallback) { 510 if (errorCallback is ZoneBinaryCallback) {
(...skipping 22 matching lines...) Expand all
545 var completeResult; 533 var completeResult;
546 try { 534 try {
547 completeResult = zone.run(listener._whenCompleteAction); 535 completeResult = zone.run(listener._whenCompleteAction);
548 } catch (e, s) { 536 } catch (e, s) {
549 if (hasError && identical(source._error.error, e)) { 537 if (hasError && identical(source._error.error, e)) {
550 listenerValueOrError = source._error; 538 listenerValueOrError = source._error;
551 } else { 539 } else {
552 listenerValueOrError = new AsyncError(e, s); 540 listenerValueOrError = new AsyncError(e, s);
553 } 541 }
554 listenerHasValue = false; 542 listenerHasValue = false;
543 return;
555 } 544 }
556 if (completeResult is Future) { 545 if (completeResult is Future) {
557 listener._isChained = true; 546 _Future result = listener.result;
547 result._isChained = true;
558 isPropagationAborted = true; 548 isPropagationAborted = true;
559 completeResult.then((ignored) { 549 completeResult.then((ignored) {
560 // Try again. Since the future is marked as chained it won't run 550 _propagateToListeners(source, new _FutureListener.chain(result));
561 // the whenComplete again.
562 _propagateToListeners(source, listener);
563 }, onError: (error, [stackTrace]) { 551 }, onError: (error, [stackTrace]) {
564 // When there is an error, we have to make the error the new 552 // When there is an error, we have to make the error the new
565 // result of the current listener. 553 // result of the current listener.
566 if (completeResult is! _Future) { 554 if (completeResult is! _Future) {
567 // This should be a rare case. 555 // This should be a rare case.
568 completeResult = new _Future(); 556 completeResult = new _Future();
569 completeResult._setError(error, stackTrace); 557 completeResult._setError(error, stackTrace);
570 } 558 }
571 _propagateToListeners(completeResult, listener); 559 _propagateToListeners(completeResult,
560 new _FutureListener.chain(result));
572 }); 561 });
573 } 562 }
574 } 563 }
575 564
576 if (!hasError) { 565 if (!hasError) {
577 if (listener._onValue != null) { 566 if (listener.handlesValue) {
578 listenerHasValue = handleValueCallback(); 567 listenerHasValue = handleValueCallback();
579 } 568 }
580 } else { 569 } else {
581 handleError(); 570 handleError();
582 } 571 }
583 if (listener._whenCompleteAction != null) { 572 if (listener.handlesComplete) {
584 handleWhenCompleteCallback(); 573 handleWhenCompleteCallback();
585 } 574 }
586 // If we changed zone, oldZone will not be null. 575 // If we changed zone, oldZone will not be null.
587 if (oldZone != null) Zone._leave(oldZone); 576 if (oldZone != null) Zone._leave(oldZone);
588 listener._onValueCallback = null;
589 listener._errorTestCallback = null;
590 listener._onErrorCallback = null;
591 listener._whenCompleteActionCallback = null;
592 577
593 if (isPropagationAborted) return; 578 if (isPropagationAborted) return;
594 // If the listener's value is a future we need to chain it. Note that 579 // If the listener's value is a future we need to chain it. Note that
595 // this can only happen if there is a callback. Since 'is' checks 580 // this can only happen if there is a callback. Since 'is' checks
596 // can be expensive, we're trying to avoid it. 581 // can be expensive, we're trying to avoid it.
597 if (listenerHasValue && 582 if (listenerHasValue &&
598 !identical(sourceValue, listenerValueOrError) && 583 !identical(sourceValue, listenerValueOrError) &&
599 listenerValueOrError is Future) { 584 listenerValueOrError is Future) {
600 Future chainSource = listenerValueOrError; 585 Future chainSource = listenerValueOrError;
601 // Shortcut if the chain-source is already completed. Just continue 586 // Shortcut if the chain-source is already completed. Just continue
602 // the loop. 587 // the loop.
588 _Future result = listener.result;
603 if (chainSource is _Future) { 589 if (chainSource is _Future) {
604 if (chainSource._isComplete) { 590 if (chainSource._isComplete) {
605 // propagate the value (simulating a tail call). 591 // propagate the value (simulating a tail call).
606 listener._isChained = true; 592 result._isChained = true;
607 source = chainSource; 593 source = chainSource;
608 listeners = listener; 594 listeners = new _FutureListener.chain(result);
609 continue; 595 continue;
610 } else { 596 } else {
611 _chainCoreFuture(chainSource, listener); 597 _chainCoreFuture(chainSource, result);
612 } 598 }
613 } else { 599 } else {
614 _chainForeignFuture(chainSource, listener); 600 _chainForeignFuture(chainSource, result);
615 } 601 }
616 return; 602 return;
617 } 603 }
618 } 604 }
605 _Future result = listener.result;
606 listeners = result._removeListeners();
619 if (listenerHasValue) { 607 if (listenerHasValue) {
620 listeners = listener._removeListeners(); 608 result._setValue(listenerValueOrError);
621 listener._setValue(listenerValueOrError);
622 } else { 609 } else {
623 listeners = listener._removeListeners();
624 AsyncError asyncError = listenerValueOrError; 610 AsyncError asyncError = listenerValueOrError;
625 listener._setError(asyncError.error, asyncError.stackTrace); 611 result._setErrorObject(asyncError);
626 } 612 }
627 // Prepare for next round. 613 // Prepare for next round.
628 source = listener; 614 source = result;
629 } 615 }
630 } 616 }
631 617
632 Future timeout(Duration timeLimit, {onTimeout()}) { 618 Future timeout(Duration timeLimit, {onTimeout()}) {
633 if (_isComplete) return new _Future.immediate(this); 619 if (_isComplete) return new _Future.immediate(this);
634 _Future result = new _Future(); 620 _Future result = new _Future();
635 Timer timer; 621 Timer timer;
636 if (onTimeout == null) { 622 if (onTimeout == null) {
637 timer = new Timer(timeLimit, () { 623 timer = new Timer(timeLimit, () {
638 result._completeError(new TimeoutException("Future not completed", 624 result._completeError(new TimeoutException("Future not completed",
(...skipping 17 matching lines...) Expand all
656 } 642 }
657 }, onError: (e, s) { 643 }, onError: (e, s) {
658 if (timer.isActive) { 644 if (timer.isActive) {
659 timer.cancel(); 645 timer.cancel();
660 result._completeError(e, s); 646 result._completeError(e, s);
661 } 647 }
662 }); 648 });
663 return result; 649 return result;
664 } 650 }
665 } 651 }
OLDNEW
« no previous file with comments | « no previous file | sdk/lib/async/schedule_microtask.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698