Skip to content

Commit

Permalink
feat: improve initial shopping list load
Browse files Browse the repository at this point in the history
  • Loading branch information
TomBursch committed Aug 11, 2023
1 parent 8da209d commit d69b052
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
54 changes: 54 additions & 0 deletions lib/cubits/shoppinglist_cubit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class ShoppinglistCubit extends Cubit<ShoppinglistCubitState> {
);
}
});
_initialLoad();
refresh();
}

Expand Down Expand Up @@ -194,6 +195,59 @@ class ShoppinglistCubit extends Cubit<ShoppinglistCubitState> {
return _refreshThread!;
}

Future<void> _initialLoad() async {
final shoppingLists = await TransactionHandler.getInstance().runTransaction(
TransactionShoppingListGet(household: household),
forceOffline: true,
);

final shoppinglist =
state.selectedShoppinglist ?? shoppingLists.firstOrNull;

if (shoppinglist == null) return;

Future<List<ShoppinglistItem>> items =
TransactionHandler.getInstance().runTransaction(
TransactionShoppingListGetItems(
shoppinglist: shoppinglist,
sorting: state.sorting,
),
forceOffline: true,
);

Future<List<Category>> categories =
TransactionHandler.getInstance().runTransaction(
TransactionCategoriesGet(household: household),
forceOffline: true,
);

final recent = TransactionHandler.getInstance().runTransaction(
TransactionShoppingListGetRecentItems(
shoppinglist: shoppinglist,
itemsCount: recentItemCountProvider(),
),
forceOffline: true,
);
List<ShoppinglistItem> loadedShoppinglistItems = await items;
final resState = ShoppinglistCubitState(
shoppinglists: shoppingLists,
selectedShoppinglist: shoppinglist,
listItems: loadedShoppinglistItems,
recentItems: await recent,
categories: await categories,
sorting: state.sorting,
selectedListItems: state.selectedListItems
.map((e) => (loadedShoppinglistItems)
.firstWhereOrNull((item) => item.id == e.id))
.whereNotNull()
.toList(),
);

if (state is LoadingShoppinglistCubitState) {
emit(resState);
}
}

// ignore: long-method
Future<void> _refresh([String? query]) async {
// Get required information
Expand Down
8 changes: 6 additions & 2 deletions lib/services/transaction_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ class TransactionHandler {
}
}

Future<T> runTransaction<T>(Transaction<T> t) async {
Future<T> runTransaction<T>(
Transaction<T> t, {
bool forceOffline = false,
}) async {
forceOffline = forceOffline || App.isForcedOffline;
if (!ApiService.getInstance().isConnected()) {
await ApiService.getInstance().refresh();
}
if (!App.isForcedOffline && ApiService.getInstance().isConnected()) {
if (!forceOffline && ApiService.getInstance().isConnected()) {
T? res = await t.runOnline();
if (res != null && (res is! bool || res)) return res;
}
Expand Down

0 comments on commit d69b052

Please sign in to comment.