Skip to content

Commit

Permalink
Split up optimistic result flush logic to two streams
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Apr 24, 2020
1 parent 46edd04 commit 3cdb60b
Showing 1 changed file with 28 additions and 24 deletions.
52 changes: 28 additions & 24 deletions exchanges/graphcache/src/cacheExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
share,
fromPromise,
fromArray,
fromValue,
buffer,
take,
mergeMap,
Expand Down Expand Up @@ -384,41 +383,46 @@ export const cacheExchange = (opts?: CacheExchangeOpts): Exchange => ({
const result$ = pipe(
merge([nonCacheOps$, cacheMissOps$]),
map(prepareForwardedOperation),
forward
forward,
share
);

// Results that can immediately be resolved
const nonOptimisticResults$ = pipe(
result$,
filter(result => !optimisticKeysToDependencies.has(result.operation.key))
);

// Prevent mutations that were previously optimistic from being flushed
// immediately and instead clear them out slowly
const resultWithUpdate$ = pipe(
const optimisticMutationCompletion$ = pipe(
result$,
filter(result => optimisticKeysToDependencies.has(result.operation.key)),
mergeMap(
(result: OperationResult): Source<OperationResult> => {
if (optimisticKeysToDependencies.has(result.operation.key)) {
mutationResultBuffer.push(result);
if (
mutationResultBuffer.length < optimisticKeysToDependencies.size
) {
return empty;
}

for (let i = 0; i < mutationResultBuffer.length; i++) {
clearLayer(store.data, mutationResultBuffer[i].operation.key);
}

const results: OperationResult[] = [];
let bufferedResult: OperationResult | void;
while ((bufferedResult = mutationResultBuffer.shift()))
results.push(updateCacheWithResult(bufferedResult));
const length = mutationResultBuffer.push(result);
if (length < optimisticKeysToDependencies.size) {
return empty;
}

return fromArray(results);
for (let i = 0; i < mutationResultBuffer.length; i++) {
clearLayer(store.data, mutationResultBuffer[i].operation.key);
}

return fromValue(updateCacheWithResult(result));
const results: OperationResult[] = [];
let bufferedResult: OperationResult | void;
while ((bufferedResult = mutationResultBuffer.shift()))
results.push(updateCacheWithResult(bufferedResult));

return fromArray(results);
}
),
filter(result => !!result)
)
);

return merge([resultWithUpdate$, cacheResult$]);
return merge([
nonOptimisticResults$,
optimisticMutationCompletion$,
cacheResult$,
]);
};
};

0 comments on commit 3cdb60b

Please sign in to comment.