OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2014, 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 gcloud.common; |
| 6 |
| 7 import 'dart:async'; |
| 8 |
| 9 /// A single page of paged results from a query. |
| 10 /// |
| 11 /// Use `next` to move to the next page. If this is the last page `next` |
| 12 /// completes with `null` |
| 13 abstract class Page<T> { |
| 14 /// The items in this page. |
| 15 List<T> get items; |
| 16 |
| 17 /// Whether this is the last page of results. |
| 18 bool get isLast; |
| 19 |
| 20 /// Move to the next page. |
| 21 /// |
| 22 /// The future returned completes with the next page or results. |
| 23 /// |
| 24 /// If [next] is called on the last page the returned future completes |
| 25 /// with `null`. |
| 26 Future<Page<T>> next({int pageSize}); |
| 27 } |
| 28 |
| 29 typedef Future<Page<T>> FirstPageProvider<T>(int pageSize); |
| 30 |
| 31 /// Helper class to turn a series of pages into a stream. |
| 32 class StreamFromPages<T> { |
| 33 static const int _PAGE_SIZE = 50; |
| 34 final FirstPageProvider _firstPageProvider; |
| 35 bool _pendingRequest = false; |
| 36 bool _paused = false; |
| 37 bool _cancelled = false; |
| 38 Page _currentPage; |
| 39 StreamController _controller; |
| 40 |
| 41 StreamFromPages(this._firstPageProvider) { |
| 42 _controller = new StreamController(sync: true, onListen: _onListen, |
| 43 onPause: _onPause, onResume: _onResume, |
| 44 onCancel: _onCancel); |
| 45 } |
| 46 |
| 47 Stream<T> get stream => _controller.stream; |
| 48 |
| 49 void _handleError(e, s) { |
| 50 _controller.addError(e, s); |
| 51 _controller.close(); |
| 52 } |
| 53 |
| 54 void _handlePage(Page<T> page) { |
| 55 if (_cancelled) return; |
| 56 _pendingRequest = false; |
| 57 _currentPage = page; |
| 58 page.items.forEach(_controller.add); |
| 59 if (page.isLast) { |
| 60 _controller.close(); |
| 61 } else if (!_paused && !_cancelled) { |
| 62 page.next().then(_handlePage, onError: _handleError); |
| 63 } |
| 64 } |
| 65 |
| 66 _onListen() { |
| 67 int pageSize = _PAGE_SIZE; |
| 68 _pendingRequest = true; |
| 69 _firstPageProvider(pageSize).then(_handlePage, onError: _handleError); |
| 70 } |
| 71 |
| 72 _onPause() { _paused = true; } |
| 73 |
| 74 _onResume() { |
| 75 _paused = false; |
| 76 if (_pendingRequest) return; |
| 77 _pendingRequest = true; |
| 78 _currentPage.next().then(_handlePage, onError: _handleError); |
| 79 } |
| 80 |
| 81 _onCancel() { |
| 82 _cancelled = true; |
| 83 } |
| 84 |
| 85 } |
OLD | NEW |