update perf

This commit is contained in:
Phuoc Nguyen
2025-12-02 17:32:20 +07:00
parent 211ebdf1d8
commit fc9b5e967f
13 changed files with 254 additions and 200 deletions

View File

@@ -1,23 +1,25 @@
/// Provider: Promotions Provider
///
/// Manages the state of promotions data using Riverpod.
/// Provides access to active promotions throughout the app.
/// Uses the same data source as news articles (single API call).
///
/// Uses AsyncNotifierProvider for automatic loading, error, and data states.
library;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/features/home/data/datasources/home_local_datasource.dart';
import 'package:worker/features/home/data/repositories/home_repository_impl.dart';
import 'package:worker/features/home/domain/entities/promotion.dart';
import 'package:worker/features/home/domain/usecases/get_promotions.dart';
import 'package:worker/features/news/presentation/providers/news_provider.dart';
part 'promotions_provider.g.dart';
/// Max number of promotions to display on home page
const int _maxPromotions = 5;
/// Promotions Provider
///
/// Fetches and caches the list of active promotions.
/// Automatically handles loading, error, and data states.
/// Uses the same data source as news articles to avoid duplicate API calls.
/// Converts NewsArticle to Promotion entity for display in PromotionSlider.
/// Limited to 5 items max.
///
/// Usage:
/// ```dart
@@ -31,33 +33,22 @@ part 'promotions_provider.g.dart';
/// );
/// ```
@riverpod
class PromotionsNotifier extends _$PromotionsNotifier {
@override
Future<List<Promotion>> build() async {
// Initialize dependencies
final localDataSource = const HomeLocalDataSourceImpl();
final repository = HomeRepositoryImpl(localDataSource: localDataSource);
final useCase = GetPromotions(repository);
Future<List<Promotion>> promotions(Ref ref) async {
// Use newsArticles provider (same API call, no duplicate request)
final articles = await ref.watch(newsArticlesProvider.future);
// Fetch promotions (only active ones)
return await useCase();
}
// Take max 5 articles and convert to Promotion
final limitedArticles = articles.take(_maxPromotions).toList();
/// Refresh promotions data
///
/// Forces a refresh from the server (when API is available).
/// Updates the cached state with fresh data.
Future<void> refresh() async {
// Set loading state
state = const AsyncValue.loading();
// Fetch fresh data
state = await AsyncValue.guard(() async {
final localDataSource = const HomeLocalDataSourceImpl();
final repository = HomeRepositoryImpl(localDataSource: localDataSource);
final useCase = GetPromotions(repository);
return await useCase.refresh();
});
}
return limitedArticles.map((article) {
final now = DateTime.now();
return Promotion(
id: article.id,
title: article.title,
description: article.excerpt,
imageUrl: article.imageUrl,
startDate: article.publishedDate,
endDate: now.add(const Duration(days: 365)), // Always active
);
}).toList();
}