From b2217c72b2a8ef075e3a41395e18fc561aabd490 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kl=C4=81vs=20Pried=C4=ABtis?= Date: Tue, 17 Sep 2019 15:10:50 +0300 Subject: [PATCH] dedupe DataLoader requests for the same item --- data_loader/lib/data_loader.dart | 19 ++++++++++++++----- data_loader/test/all_test.dart | 25 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/data_loader/lib/data_loader.dart b/data_loader/lib/data_loader.dart index 4b013609..c806f908 100644 --- a/data_loader/lib/data_loader.dart +++ b/data_loader/lib/data_loader.dart @@ -25,13 +25,22 @@ class DataLoader { var current = _queue.toList(); _queue.clear(); - var data = await loadMany(current.map((i) => i.id)); + List loadIds = + current.map((i) => i.id).toSet().toList(growable: false); - for (int i = 0; i < current.length; i++) { - var item = current[i]; + var data = await loadMany( + loadIds, + ); + + for (int i = 0; i < loadIds.length; i++) { + var id = loadIds[i]; var value = data.elementAt(i); - if (cache) _cache[item.id] = value; - item.completer.complete(value); + + if (cache) _cache[id] = value; + + current + .where((item) => item.id == id) + .forEach((item) => item.completer.complete(value)); } } diff --git a/data_loader/test/all_test.dart b/data_loader/test/all_test.dart index 5da29500..28f95eda 100644 --- a/data_loader/test/all_test.dart +++ b/data_loader/test/all_test.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:data_loader/data_loader.dart'; import 'package:test/test.dart'; @@ -18,6 +19,30 @@ void main() { expect(batch, ['0.00', '1.00', '2.00']); }); + test('dedupe', () async { + var loader = DataLoader>>((ids) { + return ids.map( + (i) => {i: ids.toList()}, + ); + }); + + var zero = loader.load(0); + var one = loader.load(1); + var two = loader.load(2); + var anotherZero = loader.load(0); + var batch = await Future.wait([zero, one, two, anotherZero]); + + expect( + batch, + [ + { 0: [0, 1, 2]}, + { 1: [0, 1, 2]}, + { 2: [0, 1, 2]}, + { 0: [0, 1, 2]}, + ], + ); + }); + group('cache', () { DataLoader uniqueLoader, noCache;