Avoid updating history too frequently.

This commit is contained in:
2025-02-14 11:46:38 +08:00
parent 22c01b4fd0
commit e7aad5f0d1
2 changed files with 19 additions and 2 deletions

View File

@@ -245,8 +245,17 @@ class HistoryManager with ChangeNotifier {
});
}
bool _haveAsyncTask = false;
/// Create a isolate to add history to prevent blocking the UI thread.
Future<void> 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.

View File

@@ -230,6 +230,10 @@ class _ReaderState extends State<Reader> 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<Reader> 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;
});
}
}