import 'dart:collection'; import 'package:flutter/foundation.dart'; typedef ComputeQueueCallback = void Function(U result); /// Compute the jobs in the queue one by one sequentially in isolate class ComputeQueue { void addJob(T event, ComputeCallback callback, ComputeQueueCallback onResult) { _queue.addLast(_Job(event, callback, onResult)); if (_queue.length == 1) { _startProcessing(); } } bool get isProcessing => _queue.isNotEmpty; Future _startProcessing() async { while (_queue.isNotEmpty) { final ev = _queue.first; try { final result = await compute(ev.callback, ev.message); ev.onResult(result); } finally { _queue.removeFirst(); } } } final _queue = Queue<_Job>(); } class _Job { const _Job(this.message, this.callback, this.onResult); final T message; final ComputeCallback callback; final ComputeQueueCallback onResult; }