perform the initial poll for devices quicker (#11356)
* perform the initial poll for devices quicker * add a Poller class * test the new Poller class
This commit is contained in:
@@ -10,6 +10,7 @@ import 'package:crypto/crypto.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:quiver/time.dart';
|
||||
|
||||
import '../globals.dart';
|
||||
import 'context.dart';
|
||||
import 'file_system.dart';
|
||||
import 'platform.dart';
|
||||
@@ -216,3 +217,42 @@ class Uuid {
|
||||
}
|
||||
|
||||
Clock get clock => context.putIfAbsent(Clock, () => const Clock());
|
||||
|
||||
typedef Future<Null> AsyncCallback();
|
||||
|
||||
/// A [Timer] inspired class that:
|
||||
/// - has a different initial value for the first callback delay
|
||||
/// - waits for a callback to be complete before it starts the next timer
|
||||
class Poller {
|
||||
Poller(this.callback, this.pollingInterval, { this.initialDelay: Duration.ZERO }) {
|
||||
new Future<Null>.delayed(initialDelay, _handleCallback);
|
||||
}
|
||||
|
||||
final AsyncCallback callback;
|
||||
final Duration initialDelay;
|
||||
final Duration pollingInterval;
|
||||
|
||||
bool _cancelled = false;
|
||||
Timer _timer;
|
||||
|
||||
Future<Null> _handleCallback() async {
|
||||
if (_cancelled)
|
||||
return;
|
||||
|
||||
try {
|
||||
await callback();
|
||||
} catch (error) {
|
||||
printTrace('Error from poller: $error');
|
||||
}
|
||||
|
||||
if (!_cancelled)
|
||||
_timer = new Timer(pollingInterval, _handleCallback);
|
||||
}
|
||||
|
||||
/// Cancels the poller.
|
||||
void cancel() {
|
||||
_cancelled = true;
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,35 +116,28 @@ abstract class PollingDeviceDiscovery extends DeviceDiscovery {
|
||||
|
||||
final String name;
|
||||
ItemListNotifier<Device> _items;
|
||||
Timer _timer;
|
||||
Poller _poller;
|
||||
|
||||
Future<List<Device>> pollingGetDevices();
|
||||
|
||||
void startPolling() {
|
||||
if (_timer == null) {
|
||||
if (_poller == null) {
|
||||
_items ??= new ItemListNotifier<Device>();
|
||||
bool _fetchingDevices = false;
|
||||
_timer = new Timer.periodic(_pollingInterval, (Timer timer) async {
|
||||
if (_fetchingDevices) {
|
||||
printTrace('Skipping device poll: already in progress');
|
||||
return;
|
||||
}
|
||||
_fetchingDevices = true;
|
||||
|
||||
_poller = new Poller(() async {
|
||||
try {
|
||||
final List<Device> devices = await pollingGetDevices().timeout(_pollingTimeout);
|
||||
_items.updateWithNewList(devices);
|
||||
} on TimeoutException {
|
||||
printTrace('Device poll timed out.');
|
||||
} finally {
|
||||
_fetchingDevices = false;
|
||||
}
|
||||
});
|
||||
}, _pollingInterval);
|
||||
}
|
||||
}
|
||||
|
||||
void stopPolling() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_poller?.cancel();
|
||||
_poller = null;
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
Reference in New Issue
Block a user