22 lines
673 B
Dart
22 lines
673 B
Dart
import 'dart:async';
|
|
import 'dart:isolate';
|
|
|
|
/// Simple worker that executes functions in a separate isolate.
|
|
/// Replacement for combine package's CombineWorker.
|
|
class IsolateWorker {
|
|
/// Execute a function in a separate isolate and return the result.
|
|
///
|
|
/// Note: The function must be a top-level function or a static method,
|
|
/// and it cannot capture non-sendable objects from the surrounding scope.
|
|
Future<T> execute<T>(T Function() computation, {bool allowSyncFallback = false}) async {
|
|
try {
|
|
return await Isolate.run(computation);
|
|
} catch (e) {
|
|
if (!allowSyncFallback) {
|
|
rethrow;
|
|
}
|
|
return computation();
|
|
}
|
|
}
|
|
}
|