dedupe DataLoader requests for the same item

This commit is contained in:
Klāvs Priedītis 2019-09-17 15:10:50 +03:00
parent b323ecc3b4
commit b2217c72b2
2 changed files with 39 additions and 5 deletions

View file

@ -25,13 +25,22 @@ class DataLoader<Id, Data> {
var current = _queue.toList(); var current = _queue.toList();
_queue.clear(); _queue.clear();
var data = await loadMany(current.map((i) => i.id)); List<Id> loadIds =
current.map((i) => i.id).toSet().toList(growable: false);
for (int i = 0; i < current.length; i++) { var data = await loadMany(
var item = current[i]; loadIds,
);
for (int i = 0; i < loadIds.length; i++) {
var id = loadIds[i];
var value = data.elementAt(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));
} }
} }

View file

@ -1,4 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'package:data_loader/data_loader.dart'; import 'package:data_loader/data_loader.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
@ -18,6 +19,30 @@ void main() {
expect(batch, ['0.00', '1.00', '2.00']); expect(batch, ['0.00', '1.00', '2.00']);
}); });
test('dedupe', () async {
var loader = DataLoader<int, Map<int, List<int>>>((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', () { group('cache', () {
DataLoader<int, _Unique> uniqueLoader, noCache; DataLoader<int, _Unique> uniqueLoader, noCache;