Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Improve startup responsiveness and targeted refreshes (#42)

Kevin GATERAfa6b6c0c6fb1
diff --git a/lib/main.dart b/lib/main.dart
index 1e0246b6..ec5102eb 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -305,8 +305,9 @@ class _AuthGateState extends State<AuthGate> {
await ProgressSyncService().init();
await EqualizerService().init();
await SleepTimerService().loadAutoSleepSettings();
- // Pre-populate Android Auto browse tree
- AndroidAutoService().refresh();
+ // Pre-populate Android Auto browse tree in background.
+ // Do not block app startup on Android Auto server refresh.
+ Future.microtask(() => AndroidAutoService().refresh());
} catch (e) {
debugPrint('Service init failed: $e');
}
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index baf161ac..36c91f04 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -584,8 +584,10 @@ class LibraryProvider extends ChangeNotifier {
_lastPersonalizedFetchAt = DateTime.now();
_lastPersonalizedFetchLibraryId = _selectedLibraryId;
await _refreshProgress();
- _personalizedSections =
- await _api!.getPersonalizedView(_selectedLibraryId!);
+ _personalizedSections = await _api!.getPersonalizedView(
+ _selectedLibraryId!,
+ include: const ['numEpisodesIncomplete'],
+ );
// Cache updatedAt timestamps for cover cache-busting
for (final section in _personalizedSections) {
for (final e in (section['entities'] as List<dynamic>? ?? [])) {
@@ -684,6 +686,16 @@ class LibraryProvider extends ChangeNotifier {
notifyListeners();
}
+ /// Lightweight refresh for views that only need up-to-date progress.
+ /// Avoids expensive personalized shelf rebuilds.
+ Future<void> refreshProgressOnly() async {
+ if (isOffline || _api == null) return;
+ await ProgressSyncService().flushPendingSync(api: _api!);
+ await _refreshProgress();
+ _localProgressOverrides.clear();
+ notifyListeners();
+ }
+
/// Fetch series for the selected library.
Future<void> loadSeries({String sort = 'addedAt', int desc = 1}) async {
if (_api == null || _selectedLibraryId == null) return;
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index 79a8450a..dbbd56e3 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -408,6 +408,12 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
}).toList();
}
+ final showBlockingLoader = lib.isLoading &&
+ books.isEmpty &&
+ !_player.hasBook &&
+ !_cast.isCasting &&
+ lib.personalizedSections.isEmpty;
+
final muted = cs.onSurfaceVariant;
final subtleBg = cs.onSurface.withValues(alpha: 0.06);
final subtleBorder = cs.onSurface.withValues(alpha: 0.08);
@@ -538,7 +544,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
),
// ── Cards (refreshable) ──
Expanded(
- child: lib.isLoading
+ child: showBlockingLoader
? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.24)))
: books.isEmpty
? _emptyState(cs, tt, effectiveOffline)
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index 84014f33..ce1c54e6 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -53,6 +53,10 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
bool _wasCasting = false;
Timer? _castDisconnectTimer;
+ // Lazily build tabs so startup on Absorbing does not initialize Home/Library
+ // work until the user actually visits those tabs.
+ final List<Widget?> _pages = List<Widget?>.filled(5, null, growable: false);
+
void _switchToAbsorbing() {
if (mounted) {
_navigateTo(2);
@@ -65,23 +69,38 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
void _navigateTo(int index) {
if (index == _currentIndex) return;
+ _ensurePageBuilt(index);
setState(() {
_currentIndex = index;
});
}
- late final _pages = [
- const HomeScreen(),
- LibraryScreen(key: _libraryKey),
- AbsorbingScreen(key: AbsorbingScreen.globalKey),
- const StatsScreen(),
- const SettingsScreen(),
- ];
+ void _ensurePageBuilt(int index) {
+ if (_pages[index] != null) return;
+ switch (index) {
+ case 0:
+ _pages[index] = const HomeScreen();
+ break;
+ case 1:
+ _pages[index] = LibraryScreen(key: _libraryKey);
+ break;
+ case 2:
+ _pages[index] = AbsorbingScreen(key: AbsorbingScreen.globalKey);
+ break;
+ case 3:
+ _pages[index] = const StatsScreen();
+ break;
+ case 4:
+ _pages[index] = const SettingsScreen();
+ break;
+ }
+ }
@override
void initState() {
super.initState();
_instance = this;
+ _ensurePageBuilt(_currentIndex);
_playerHadBook = _player.hasBook;
_wasPlaying = _player.isPlaying;
_lastItemId = _player.currentItemId;
@@ -185,7 +204,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
if (state == AppLifecycleState.resumed) {
_castDisconnectTimer?.cancel();
_castDisconnectTimer = null;
- _refreshData();
+ _refreshDataForTab(_currentIndex);
// Check auto sleep in case we resumed into the window
SleepTimerService().checkAutoSleep();
} else if (state == AppLifecycleState.paused) {
@@ -206,13 +225,19 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
DateTime? _lastRefresh;
static const _refreshCooldown = Duration(minutes: 1);
- void _refreshData() {
+ void _refreshDataForTab(int tabIndex) {
final now = DateTime.now();
final lib = context.read<LibraryProvider>();
-
+
// Always sync local progress (cheap, no network)
lib.refreshLocalProgress();
-
+
+ // Tabs that do not need full personalized shelf rebuilds.
+ if (tabIndex == 1 || tabIndex == 2 || tabIndex == 3) {
+ unawaited(lib.refreshProgressOnly());
+ return;
+ }
+
// Only do a full server refresh if enough time has passed
if (_lastRefresh == null || now.difference(_lastRefresh!) > _refreshCooldown) {
_lastRefresh = now;
@@ -248,7 +273,10 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
child: Scaffold(
body: IndexedStack(
index: _currentIndex,
- children: _pages,
+ children: List<Widget>.generate(
+ _pages.length,
+ (i) => _pages[i] ?? const SizedBox.shrink(),
+ ),
),
bottomNavigationBar: Column(
mainAxisSize: MainAxisSize.min,
@@ -264,7 +292,9 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
}
_navigateTo(i);
// Refresh data on switching to Library, Home, Absorbing, or Stats
- if (i == 0 || i == 1 || i == 2 || i == 3) _refreshData();
+ if (i == 0 || i == 1 || i == 2 || i == 3) {
+ _refreshDataForTab(i);
+ }
},
destinations: _buildDestinations(context),
),
diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dart
index e97bce30..d01e09e3 100644
--- a/lib/services/android_auto_service.dart
+++ b/lib/services/android_auto_service.dart
@@ -314,7 +314,12 @@ class AndroidAutoService {
// ── Continue Listening (from default library) ──
final defaultLibId = await getDefaultLibraryId();
if (defaultLibId != null) {
- final sections = await api.getPersonalizedView(defaultLibId);
+ final sections = await api.getPersonalizedView(
+ defaultLibId,
+ include: const ['numEpisodesIncomplete'],
+ shelves: const ['continue-listening', 'continue-series'],
+ limit: 10,
+ );
final continueEntries = <AutoBookEntry>[];
final seenIds = <String>{};
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index ff880776..6c582994 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -139,16 +139,37 @@ class ApiService {
/// Get the personalized home view for a library.
/// Returns sections like "continue-listening", "recently-added", "discover", etc.
- Future<List<dynamic>> getPersonalizedView(String libraryId) async {
+ Future<List<dynamic>> getPersonalizedView(
+ String libraryId, {
+ bool minified = true,
+ List<String> include = const ['numEpisodesIncomplete'],
+ List<String>? shelves,
+ int? limit,
+ }) async {
try {
+ final query = <String, String>{};
+ if (minified) query['minified'] = '1';
+ if (include.isNotEmpty) query['include'] = include.join(',');
+ if (shelves != null && shelves.isNotEmpty) {
+ query['shelves'] = shelves.join(',');
+ }
+ if (limit != null) query['limit'] = '$limit';
+
final response = await http.get(
- Uri.parse(
- '$_cleanBaseUrl/api/libraries/$libraryId/personalized'),
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/personalized')
+ .replace(queryParameters: query.isEmpty ? null : query),
headers: _headers,
).timeout(const Duration(seconds: 15));
if (response.statusCode == 200) {
- return jsonDecode(response.body) as List<dynamic>;
+ final data = jsonDecode(response.body);
+ if (data is List<dynamic>) return data;
+ if (data is Map<String, dynamic>) {
+ final shelvesData = data['shelves'];
+ if (shelvesData is List<dynamic>) return shelvesData;
+ final results = data['results'];
+ if (results is List<dynamic>) return results;
+ }
}
} catch (e) {
// ignore
@@ -849,11 +870,7 @@ class ApiService {
Future<Map<String, dynamic>?> searchAudibleRating(
String title, String? author) async {
try {
- // Use the ABS server's search endpoint to query Audible for the book
- final query = author != null && author.isNotEmpty
- ? '$title $author'
- : title;
- final encoded = Uri.encodeQueryComponent(query);
+ // Use the ABS server's search endpoint to query Audible for the book.
final response = await http.get(
Uri.parse(
'$_cleanBaseUrl/api/search/covers?title=${Uri.encodeQueryComponent(title)}'