feat: Implement batch insertion for Pokémon and utilize it for more efficient initial data synchronization.
This commit is contained in:
parent
fbf37e6861
commit
112d0136c9
@ -43,6 +43,21 @@ class PokedexDatabase {
|
|||||||
onDatabaseUpdate.value++;
|
onDatabaseUpdate.value++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Méthode qui permet d'insérer plusieurs Pokémon d'un coup (plus performant)
|
||||||
|
static Future<void> batchInsertPokemon(List<Pokemon> pokemonList) async {
|
||||||
|
Database db = await getDatabase();
|
||||||
|
Batch batch = db.batch();
|
||||||
|
for (var pokemon in pokemonList) {
|
||||||
|
batch.insert(
|
||||||
|
'pokemon',
|
||||||
|
pokemon.toJson(),
|
||||||
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await batch.commit(noResult: true);
|
||||||
|
onDatabaseUpdate.value++;
|
||||||
|
}
|
||||||
|
|
||||||
// Méthode qui permet de récupérer la liste des pokémons dans la base de données
|
// Méthode qui permet de récupérer la liste des pokémons dans la base de données
|
||||||
static Future<List<Pokemon>> getPokemonList() async {
|
static Future<List<Pokemon>> getPokemonList() async {
|
||||||
Database database = await getDatabase();
|
Database database = await getDatabase();
|
||||||
|
|||||||
@ -38,18 +38,16 @@ class _PokemonListPageState extends State<PokemonListPage> {
|
|||||||
|
|
||||||
final count = await PokedexDatabase.getCaughtCount();
|
final count = await PokedexDatabase.getCaughtCount();
|
||||||
|
|
||||||
// Check if database is empty for initial sync
|
// Check if database needs sync (less than 1025 pokemon)
|
||||||
List<Pokemon> localData = await PokedexDatabase.getPokemonList();
|
List<Pokemon> localData = await PokedexDatabase.getPokemonList();
|
||||||
if(localData.isEmpty) {
|
if (localData.length < 1025) {
|
||||||
try {
|
try {
|
||||||
final List<Pokemon> remoteData = await PokemonApi.getAllPokemon();
|
final List<Pokemon> remoteData = await PokemonApi.getAllPokemon();
|
||||||
// Insert all
|
// Insert all missing pokemon using batch for performance
|
||||||
for (var p in remoteData) {
|
await PokedexDatabase.batchInsertPokemon(remoteData);
|
||||||
await PokedexDatabase.insertPokemon(p);
|
|
||||||
}
|
|
||||||
localData = await PokedexDatabase.getPokemonList();
|
localData = await PokedexDatabase.getPokemonList();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint(e.toString());
|
debugPrint('Sync Error: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user