Stream logging from attached debugger on iOS 13+ (#66399)
This commit is contained in:
@@ -213,6 +213,9 @@ class IOSDevice extends Device {
|
||||
|
||||
DevicePortForwarder _portForwarder;
|
||||
|
||||
@visibleForTesting
|
||||
IOSDeployDebugger iosDeployDebugger;
|
||||
|
||||
@override
|
||||
Future<bool> get isLocalEmulator async => false;
|
||||
|
||||
@@ -396,23 +399,45 @@ class IOSDevice extends Device {
|
||||
timeout: timeoutConfiguration.slowOperation);
|
||||
try {
|
||||
ProtocolDiscovery observatoryDiscovery;
|
||||
int installationResult = 1;
|
||||
if (debuggingOptions.debuggingEnabled) {
|
||||
_logger.printTrace('Debugging is enabled, connecting to observatory');
|
||||
final DeviceLogReader deviceLogReader = getLogReader(app: package);
|
||||
|
||||
// If the device supports syslog reading, prefer launching the app without
|
||||
// attaching the debugger to avoid the overhead of the unnecessary extra running process.
|
||||
if (majorSdkVersion >= IOSDeviceLogReader.minimumUniversalLoggingSdkVersion) {
|
||||
iosDeployDebugger = _iosDeploy.prepareDebuggerForLaunch(
|
||||
deviceId: id,
|
||||
bundlePath: bundle.path,
|
||||
launchArguments: launchArguments,
|
||||
interfaceType: interfaceType,
|
||||
);
|
||||
|
||||
if (deviceLogReader is IOSDeviceLogReader) {
|
||||
deviceLogReader.debuggerStream = iosDeployDebugger;
|
||||
}
|
||||
}
|
||||
observatoryDiscovery = ProtocolDiscovery.observatory(
|
||||
getLogReader(app: package),
|
||||
deviceLogReader,
|
||||
portForwarder: portForwarder,
|
||||
throttleDuration: fallbackPollingDelay,
|
||||
throttleTimeout: fallbackThrottleTimeout ?? const Duration(seconds: 5),
|
||||
hostPort: debuggingOptions.hostVmServicePort,
|
||||
devicePort: debuggingOptions.deviceVmServicePort,
|
||||
ipv6: ipv6,
|
||||
throttleTimeout: fallbackThrottleTimeout ?? const Duration(seconds: 1),
|
||||
);
|
||||
}
|
||||
final int installationResult = await _iosDeploy.runApp(
|
||||
deviceId: id,
|
||||
bundlePath: bundle.path,
|
||||
launchArguments: launchArguments,
|
||||
interfaceType: interfaceType,
|
||||
);
|
||||
if (iosDeployDebugger == null) {
|
||||
installationResult = await _iosDeploy.launchApp(
|
||||
deviceId: id,
|
||||
bundlePath: bundle.path,
|
||||
launchArguments: launchArguments,
|
||||
interfaceType: interfaceType,
|
||||
);
|
||||
} else {
|
||||
installationResult = await iosDeployDebugger.launchAndAttach() ? 0 : 1;
|
||||
}
|
||||
if (installationResult != 0) {
|
||||
_logger.printError('Could not run ${bundle.path} on $id.');
|
||||
_logger.printError('Try launching Xcode and selecting "Product > Run" to fix the problem:');
|
||||
@@ -466,7 +491,11 @@ class IOSDevice extends Device {
|
||||
IOSApp app, {
|
||||
String userIdentifier,
|
||||
}) async {
|
||||
// Currently we don't have a way to stop an app running on iOS.
|
||||
// If the debugger is not attached, killing the ios-deploy process won't stop the app.
|
||||
if (iosDeployDebugger!= null && iosDeployDebugger.debuggerAttached) {
|
||||
// Avoid null.
|
||||
return iosDeployDebugger?.exit() == true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -656,6 +685,13 @@ class IOSDeviceLogReader extends DeviceLogReader {
|
||||
// Matches a syslog line from any app.
|
||||
RegExp _anyLineRegex;
|
||||
|
||||
// Logging from native code/Flutter engine is prefixed by timestamp and process metadata:
|
||||
// 2020-09-15 19:15:10.931434-0700 Runner[541:226276] Did finish launching.
|
||||
// 2020-09-15 19:15:10.931434-0700 Runner[541:226276] [Category] Did finish launching.
|
||||
//
|
||||
// Logging from the dart code has no prefixing metadata.
|
||||
final RegExp _debuggerLoggingRegex = RegExp(r'^\S* \S* \S*\[[0-9:]*] (.*)');
|
||||
|
||||
StreamController<String> _linesController;
|
||||
List<StreamSubscription<void>> _loggingSubscriptions;
|
||||
|
||||
@@ -672,10 +708,10 @@ class IOSDeviceLogReader extends DeviceLogReader {
|
||||
_connectedVMService = connectedVmService;
|
||||
}
|
||||
|
||||
static const int _minimumUniversalLoggingSdkVersion = 13;
|
||||
static const int minimumUniversalLoggingSdkVersion = 13;
|
||||
|
||||
Future<void> _listenToUnifiedLoggingEvents(vm_service.VmService connectedVmService) async {
|
||||
if (_majorSdkVersion < _minimumUniversalLoggingSdkVersion) {
|
||||
if (_majorSdkVersion < minimumUniversalLoggingSdkVersion) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -692,6 +728,10 @@ class IOSDeviceLogReader extends DeviceLogReader {
|
||||
}
|
||||
|
||||
void logMessage(vm_service.Event event) {
|
||||
if (_iosDeployDebugger != null && _iosDeployDebugger.debuggerAttached) {
|
||||
// Prefer the more complete logs from the attached debugger.
|
||||
return;
|
||||
}
|
||||
final String message = processVmServiceMessage(event);
|
||||
if (message.isNotEmpty) {
|
||||
_linesController.add(message);
|
||||
@@ -704,9 +744,29 @@ class IOSDeviceLogReader extends DeviceLogReader {
|
||||
]);
|
||||
}
|
||||
|
||||
/// Log reader will listen to [debugger.logLines] and will detach debugger on dispose.
|
||||
set debuggerStream(IOSDeployDebugger debugger) {
|
||||
// Logging is gathered from syslog on iOS 13 and earlier.
|
||||
if (_majorSdkVersion < minimumUniversalLoggingSdkVersion) {
|
||||
return;
|
||||
}
|
||||
_iosDeployDebugger = debugger;
|
||||
// Add the debugger logs to the controller created on initialization.
|
||||
_loggingSubscriptions.add(debugger.logLines.listen(
|
||||
(String line) => _linesController.add(_debuggerLineHandler(line)),
|
||||
onError: _linesController.addError,
|
||||
onDone: _linesController.close,
|
||||
cancelOnError: true,
|
||||
));
|
||||
}
|
||||
IOSDeployDebugger _iosDeployDebugger;
|
||||
|
||||
// Strip off the logging metadata (leave the category), or just echo the line.
|
||||
String _debuggerLineHandler(String line) => _debuggerLoggingRegex?.firstMatch(line)?.group(1) ?? line;
|
||||
|
||||
void _listenToSysLog() {
|
||||
// syslog is not written on iOS 13+.
|
||||
if (_majorSdkVersion >= _minimumUniversalLoggingSdkVersion) {
|
||||
if (_majorSdkVersion >= minimumUniversalLoggingSdkVersion) {
|
||||
return;
|
||||
}
|
||||
_iMobileDevice.startLogger(_deviceId).then<void>((Process process) {
|
||||
@@ -763,6 +823,7 @@ class IOSDeviceLogReader extends DeviceLogReader {
|
||||
loggingSubscription.cancel();
|
||||
}
|
||||
_idevicesyslogProcess?.kill();
|
||||
_iosDeployDebugger?.detach();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,29 @@ class FallbackDiscovery {
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
final Uri result = await _protocolDiscovery.uri;
|
||||
if (result != null) {
|
||||
UsageEvent(
|
||||
_kEventName,
|
||||
'log-success',
|
||||
flutterUsage: _flutterUsage,
|
||||
).send();
|
||||
return result;
|
||||
}
|
||||
} on ArgumentError {
|
||||
// In the event of an invalid InternetAddress, this code attempts to catch
|
||||
// an ArgumentError from protocol_discovery.dart
|
||||
} on Exception catch (err) {
|
||||
_logger.printTrace(err.toString());
|
||||
}
|
||||
_logger.printTrace('Failed to connect with log scanning, falling back to mDNS');
|
||||
UsageEvent(
|
||||
_kEventName,
|
||||
'log-failure',
|
||||
flutterUsage: _flutterUsage,
|
||||
).send();
|
||||
|
||||
try {
|
||||
final Uri result = await _mDnsObservatoryDiscovery.getObservatoryUri(
|
||||
packageId,
|
||||
@@ -99,35 +122,12 @@ class FallbackDiscovery {
|
||||
} on Exception catch (err) {
|
||||
_logger.printTrace(err.toString());
|
||||
}
|
||||
_logger.printTrace('Failed to connect with mDNS, falling back to log scanning');
|
||||
_logger.printTrace('Failed to connect with mDNS');
|
||||
UsageEvent(
|
||||
_kEventName,
|
||||
'mdns-failure',
|
||||
flutterUsage: _flutterUsage,
|
||||
).send();
|
||||
|
||||
try {
|
||||
final Uri result = await _protocolDiscovery.uri;
|
||||
if (result != null) {
|
||||
UsageEvent(
|
||||
_kEventName,
|
||||
'fallback-success',
|
||||
flutterUsage: _flutterUsage,
|
||||
).send();
|
||||
return result;
|
||||
}
|
||||
} on ArgumentError {
|
||||
// In the event of an invalid InternetAddress, this code attempts to catch
|
||||
// an ArgumentError from protocol_discovery.dart
|
||||
} on Exception catch (err) {
|
||||
_logger.printTrace(err.toString());
|
||||
}
|
||||
_logger.printTrace('Failed to connect with log scanning');
|
||||
UsageEvent(
|
||||
_kEventName,
|
||||
'fallback-failure',
|
||||
flutterUsage: _flutterUsage,
|
||||
).send();
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ class FallbackDiscovery {
|
||||
assumedWsUri = Uri.parse('ws://localhost:$hostPort/ws');
|
||||
} on Exception catch (err) {
|
||||
_logger.printTrace(err.toString());
|
||||
_logger.printTrace('Failed to connect directly, falling back to mDNS');
|
||||
_logger.printTrace('Failed to connect directly, falling back to log scanning');
|
||||
_sendFailureEvent(err, assumedDevicePort);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2,15 +2,20 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:process/process.dart';
|
||||
|
||||
import '../artifacts.dart';
|
||||
import '../base/common.dart';
|
||||
import '../base/io.dart';
|
||||
import '../base/logger.dart';
|
||||
import '../base/platform.dart';
|
||||
import '../base/process.dart';
|
||||
import '../build_info.dart';
|
||||
import '../cache.dart';
|
||||
import '../convert.dart';
|
||||
import 'code_signing.dart';
|
||||
import 'devices.dart';
|
||||
|
||||
@@ -107,10 +112,47 @@ class IOSDeploy {
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns [IOSDeployDebugger] wrapping attached debugger logic.
|
||||
///
|
||||
/// This method does not install the app. Call [IOSDeployDebugger.launchAndAttach()]
|
||||
/// to install and attach the debugger to the specified app bundle.
|
||||
IOSDeployDebugger prepareDebuggerForLaunch({
|
||||
@required String deviceId,
|
||||
@required String bundlePath,
|
||||
@required List<String> launchArguments,
|
||||
@required IOSDeviceInterface interfaceType,
|
||||
}) {
|
||||
// Interactive debug session to support sending the lldb detach command.
|
||||
final List<String> launchCommand = <String>[
|
||||
'script',
|
||||
'-t',
|
||||
'0',
|
||||
'/dev/null',
|
||||
_binaryPath,
|
||||
'--id',
|
||||
deviceId,
|
||||
'--bundle',
|
||||
bundlePath,
|
||||
'--debug',
|
||||
if (interfaceType != IOSDeviceInterface.network)
|
||||
'--no-wifi',
|
||||
if (launchArguments.isNotEmpty) ...<String>[
|
||||
'--args',
|
||||
launchArguments.join(' '),
|
||||
],
|
||||
];
|
||||
return IOSDeployDebugger(
|
||||
launchCommand: launchCommand,
|
||||
logger: _logger,
|
||||
processUtils: _processUtils,
|
||||
iosDeployEnv: iosDeployEnv,
|
||||
);
|
||||
}
|
||||
|
||||
/// Installs and then runs the specified app bundle.
|
||||
///
|
||||
/// Uses ios-deploy and returns the exit code.
|
||||
Future<int> runApp({
|
||||
Future<int> launchApp({
|
||||
@required String deviceId,
|
||||
@required String bundlePath,
|
||||
@required List<String> launchArguments,
|
||||
@@ -169,30 +211,210 @@ class IOSDeploy {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Maps stdout line stream. Must return original line.
|
||||
String _monitorFailure(String stdout) {
|
||||
// Installation issues.
|
||||
if (stdout.contains(noProvisioningProfileErrorOne) || stdout.contains(noProvisioningProfileErrorTwo)) {
|
||||
_logger.printError(noProvisioningProfileInstruction, emphasis: true);
|
||||
String _monitorFailure(String stdout) => _monitorIOSDeployFailure(stdout, _logger);
|
||||
}
|
||||
|
||||
/// lldb attach state flow.
|
||||
enum _IOSDeployDebuggerState {
|
||||
detached,
|
||||
launching,
|
||||
attached,
|
||||
}
|
||||
|
||||
/// Wrapper to launch app and attach the debugger with ios-deploy.
|
||||
class IOSDeployDebugger {
|
||||
IOSDeployDebugger({
|
||||
@required Logger logger,
|
||||
@required ProcessUtils processUtils,
|
||||
@required List<String> launchCommand,
|
||||
@required Map<String, String> iosDeployEnv,
|
||||
}) : _processUtils = processUtils,
|
||||
_logger = logger,
|
||||
_launchCommand = launchCommand,
|
||||
_iosDeployEnv = iosDeployEnv,
|
||||
_debuggerState = _IOSDeployDebuggerState.detached;
|
||||
|
||||
/// Create a [IOSDeployDebugger] for testing.
|
||||
///
|
||||
/// Sets the command to "ios-deploy" and environment to an empty map.
|
||||
@visibleForTesting
|
||||
factory IOSDeployDebugger.test({
|
||||
@required ProcessManager processManager,
|
||||
Logger logger,
|
||||
}) {
|
||||
final Logger debugLogger = logger ?? BufferLogger.test();
|
||||
return IOSDeployDebugger(
|
||||
logger: debugLogger,
|
||||
processUtils: ProcessUtils(logger: debugLogger, processManager: processManager),
|
||||
launchCommand: <String>['ios-deploy'],
|
||||
iosDeployEnv: <String, String>{},
|
||||
);
|
||||
}
|
||||
|
||||
final Logger _logger;
|
||||
final ProcessUtils _processUtils;
|
||||
final List<String> _launchCommand;
|
||||
final Map<String, String> _iosDeployEnv;
|
||||
|
||||
Process _iosDeployProcess;
|
||||
|
||||
Stream<String> get logLines => _debuggerOutput.stream;
|
||||
final StreamController<String> _debuggerOutput = StreamController<String>.broadcast();
|
||||
|
||||
bool get debuggerAttached => _debuggerState == _IOSDeployDebuggerState.attached;
|
||||
_IOSDeployDebuggerState _debuggerState;
|
||||
|
||||
// (lldb) run
|
||||
// https://github.com/ios-control/ios-deploy/blob/1.11.2-beta.1/src/ios-deploy/ios-deploy.m#L51
|
||||
static final RegExp _lldbRun = RegExp(r'\(lldb\)\s*run');
|
||||
|
||||
// (lldb) run
|
||||
// https://github.com/ios-control/ios-deploy/blob/1.11.2-beta.1/src/ios-deploy/ios-deploy.m#L51
|
||||
static final RegExp _lldbProcessExit = RegExp(r'Process \d* exited with status =');
|
||||
|
||||
/// Launch the app on the device, and attach the debugger.
|
||||
///
|
||||
/// Returns whether or not the debugger successfully attached.
|
||||
Future<bool> launchAndAttach() async {
|
||||
// Return when the debugger attaches, or the ios-deploy process exits.
|
||||
final Completer<bool> debuggerCompleter = Completer<bool>();
|
||||
try {
|
||||
_iosDeployProcess = await _processUtils.start(
|
||||
_launchCommand,
|
||||
environment: _iosDeployEnv,
|
||||
);
|
||||
String lastLineFromDebugger;
|
||||
final StreamSubscription<String> stdoutSubscription = _iosDeployProcess.stdout
|
||||
.transform<String>(utf8.decoder)
|
||||
.transform<String>(const LineSplitter())
|
||||
.listen((String line) {
|
||||
_monitorIOSDeployFailure(line, _logger);
|
||||
|
||||
// (lldb) run
|
||||
// success
|
||||
// 2020-09-15 13:42:25.185474-0700 Runner[477:181141] flutter: Observatory listening on http://127.0.0.1:57782/
|
||||
if (_lldbRun.hasMatch(line)) {
|
||||
_logger.printTrace(line);
|
||||
_debuggerState = _IOSDeployDebuggerState.launching;
|
||||
return;
|
||||
}
|
||||
// Next line after "run" must be "success", or the attach failed.
|
||||
// Example: "error: process launch failed"
|
||||
if (_debuggerState == _IOSDeployDebuggerState.launching) {
|
||||
_logger.printTrace(line);
|
||||
final bool attachSuccess = line == 'success';
|
||||
_debuggerState = attachSuccess ? _IOSDeployDebuggerState.attached : _IOSDeployDebuggerState.detached;
|
||||
if (!debuggerCompleter.isCompleted) {
|
||||
debuggerCompleter.complete(attachSuccess);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (line.contains('PROCESS_STOPPED') ||
|
||||
line.contains('PROCESS_EXITED') ||
|
||||
_lldbProcessExit.hasMatch(line)) {
|
||||
// The app exited or crashed, so stop echoing the output.
|
||||
// Don't pass any further ios-deploy debugging messages to the log reader after it exits.
|
||||
_debuggerState = _IOSDeployDebuggerState.detached;
|
||||
_logger.printTrace(line);
|
||||
if (!debuggerCompleter.isCompleted) {
|
||||
debuggerCompleter.complete(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (_debuggerState != _IOSDeployDebuggerState.attached) {
|
||||
_logger.printTrace(line);
|
||||
return;
|
||||
}
|
||||
if (lastLineFromDebugger != null && lastLineFromDebugger.isNotEmpty && line.isEmpty) {
|
||||
// The lldb console stream from ios-deploy is separated lines by an extra \r\n.
|
||||
// To avoid all lines being double spaced, if the last line from the
|
||||
// debugger was not an empty line, skip this empty line.
|
||||
// This will still cause "legit" logged newlines to be doubled...
|
||||
} else {
|
||||
_debuggerOutput.add(line);
|
||||
}
|
||||
lastLineFromDebugger = line;
|
||||
});
|
||||
final StreamSubscription<String> stderrSubscription = _iosDeployProcess.stderr
|
||||
.transform<String>(utf8.decoder)
|
||||
.transform<String>(const LineSplitter())
|
||||
.listen((String line) {
|
||||
_monitorIOSDeployFailure(line, _logger);
|
||||
_logger.printTrace(line);
|
||||
});
|
||||
unawaited(_iosDeployProcess.exitCode.then((int status) {
|
||||
_logger.printTrace('ios-deploy exited with code $exitCode');
|
||||
_debuggerState = _IOSDeployDebuggerState.detached;
|
||||
unawaited(stdoutSubscription.cancel());
|
||||
unawaited(stderrSubscription.cancel());
|
||||
}).whenComplete(() async {
|
||||
if (_debuggerOutput.hasListener) {
|
||||
// Tell listeners the process died.
|
||||
await _debuggerOutput.close();
|
||||
}
|
||||
if (!debuggerCompleter.isCompleted) {
|
||||
debuggerCompleter.complete(false);
|
||||
}
|
||||
_iosDeployProcess = null;
|
||||
}));
|
||||
} on ProcessException catch (exception, stackTrace) {
|
||||
_logger.printTrace('ios-deploy failed: $exception');
|
||||
_debuggerState = _IOSDeployDebuggerState.detached;
|
||||
_debuggerOutput.addError(exception, stackTrace);
|
||||
} on ArgumentError catch (exception, stackTrace) {
|
||||
_logger.printTrace('ios-deploy failed: $exception');
|
||||
_debuggerState = _IOSDeployDebuggerState.detached;
|
||||
_debuggerOutput.addError(exception, stackTrace);
|
||||
}
|
||||
// Wait until the debugger attaches, or the attempt fails.
|
||||
return debuggerCompleter.future;
|
||||
}
|
||||
|
||||
bool exit() {
|
||||
final bool success = (_iosDeployProcess == null) || _iosDeployProcess.kill();
|
||||
_iosDeployProcess = null;
|
||||
return success;
|
||||
}
|
||||
|
||||
void detach() {
|
||||
if (!debuggerAttached) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Detach lldb from the app process.
|
||||
_iosDeployProcess?.stdin?.writeln('process detach');
|
||||
_debuggerState = _IOSDeployDebuggerState.detached;
|
||||
} on SocketException catch (error) {
|
||||
// Best effort, try to detach, but maybe the app already exited or already detached.
|
||||
_logger.printTrace('Could not detach from debugger: $error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Maps stdout line stream. Must return original line.
|
||||
String _monitorIOSDeployFailure(String stdout, Logger logger) {
|
||||
// Installation issues.
|
||||
if (stdout.contains(noProvisioningProfileErrorOne) || stdout.contains(noProvisioningProfileErrorTwo)) {
|
||||
logger.printError(noProvisioningProfileInstruction, emphasis: true);
|
||||
|
||||
// Launch issues.
|
||||
} else if (stdout.contains(deviceLockedError)) {
|
||||
_logger.printError('''
|
||||
} else if (stdout.contains(deviceLockedError)) {
|
||||
logger.printError('''
|
||||
═══════════════════════════════════════════════════════════════════════════════════
|
||||
Your device is locked. Unlock your device first before running.
|
||||
═══════════════════════════════════════════════════════════════════════════════════''',
|
||||
emphasis: true);
|
||||
} else if (stdout.contains(unknownAppLaunchError)) {
|
||||
_logger.printError('''
|
||||
emphasis: true);
|
||||
} else if (stdout.contains(unknownAppLaunchError)) {
|
||||
logger.printError('''
|
||||
═══════════════════════════════════════════════════════════════════════════════════
|
||||
Error launching app. Try launching from within Xcode via:
|
||||
open ios/Runner.xcworkspace
|
||||
|
||||
Your Xcode version may be too old for your iOS version.
|
||||
═══════════════════════════════════════════════════════════════════════════════════''',
|
||||
emphasis: true);
|
||||
}
|
||||
|
||||
return stdout;
|
||||
emphasis: true);
|
||||
}
|
||||
|
||||
return stdout;
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ class ProtocolDiscovery {
|
||||
factory ProtocolDiscovery.observatory(
|
||||
DeviceLogReader logReader, {
|
||||
DevicePortForwarder portForwarder,
|
||||
Duration throttleDuration = const Duration(milliseconds: 200),
|
||||
Duration throttleDuration,
|
||||
Duration throttleTimeout,
|
||||
@required int hostPort,
|
||||
@required int devicePort,
|
||||
@@ -45,7 +45,7 @@ class ProtocolDiscovery {
|
||||
logReader,
|
||||
kObservatoryService,
|
||||
portForwarder: portForwarder,
|
||||
throttleDuration: throttleDuration,
|
||||
throttleDuration: throttleDuration ?? const Duration(milliseconds: 200),
|
||||
throttleTimeout: throttleTimeout,
|
||||
hostPort: hostPort,
|
||||
devicePort: devicePort,
|
||||
@@ -225,7 +225,7 @@ class _BufferedStreamController<T> {
|
||||
///
|
||||
/// For example, consider a `waitDuration` of `10ms`, and list of event names
|
||||
/// and arrival times: `a (0ms), b (5ms), c (11ms), d (21ms)`.
|
||||
/// The events `c` and `d` will be produced as a result.
|
||||
/// The events `a`, `c`, and `d` will be produced as a result.
|
||||
StreamTransformer<S, S> _throttle<S>({
|
||||
@required Duration waitDuration,
|
||||
}) {
|
||||
@@ -240,10 +240,13 @@ StreamTransformer<S, S> _throttle<S>({
|
||||
handleData: (S value, EventSink<S> sink) {
|
||||
latestLine = value;
|
||||
|
||||
final bool isFirstMessage = lastExecution == null;
|
||||
final int currentTime = DateTime.now().millisecondsSinceEpoch;
|
||||
lastExecution ??= currentTime;
|
||||
final int remainingTime = currentTime - lastExecution;
|
||||
final int nextExecutionTime = remainingTime > waitDuration.inMilliseconds
|
||||
|
||||
// Always send the first event immediately.
|
||||
final int nextExecutionTime = isFirstMessage || remainingTime > waitDuration.inMilliseconds
|
||||
? 0
|
||||
: waitDuration.inMilliseconds - remainingTime;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user