Merge pull request #34 from klavs/master

dedupe DataLoader requests for the same item
This commit is contained in:
Tobe Osakwe 2019-11-22 08:41:33 -05:00 committed by GitHub
commit a3bde43132
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 5 deletions

View file

@ -25,13 +25,22 @@ class DataLoader<Id, Data> {
var current = _queue.toList();
_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 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));
}
}

View file

@ -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<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', () {
DataLoader<int, _Unique> uniqueLoader, noCache;