diff --git a/lib/foundation/history.dart b/lib/foundation/history.dart index 00d96d1..5ca6236 100644 --- a/lib/foundation/history.dart +++ b/lib/foundation/history.dart @@ -245,8 +245,17 @@ class HistoryManager with ChangeNotifier { }); } + bool _haveAsyncTask = false; + + /// Create a isolate to add history to prevent blocking the UI thread. Future addHistoryAsync(History newItem) async { - _addHistoryAsync(_db.handle.address, newItem); + while (_haveAsyncTask) { + await Future.delayed(Duration(milliseconds: 20)); + } + + _haveAsyncTask = true; + await _addHistoryAsync(_db.handle.address, newItem); + _haveAsyncTask = false; } /// add history. if exists, update time. diff --git a/lib/pages/reader/reader.dart b/lib/pages/reader/reader.dart index 11fcf89..ed1cb71 100644 --- a/lib/pages/reader/reader.dart +++ b/lib/pages/reader/reader.dart @@ -230,6 +230,10 @@ class _ReaderState extends State with _ReaderLocation, _ReaderWindow { updateHistory(); } + /// Prevent multiple history updates in a short time. + /// `HistoryManager().addHistoryAsync` is a high-cost operation because it creates a new isolate. + Timer? _updateHistoryTimer; + void updateHistory() { if (history != null) { history!.page = page; @@ -239,7 +243,11 @@ class _ReaderState extends State with _ReaderLocation, _ReaderWindow { } history!.readEpisode.add(chapter); history!.time = DateTime.now(); - HistoryManager().addHistoryAsync(history!); + _updateHistoryTimer?.cancel(); + _updateHistoryTimer = Timer(const Duration(seconds: 1), () { + HistoryManager().addHistoryAsync(history!); + _updateHistoryTimer = null; + }); } }