From 3cdb60b548d58abc7e7876094a495d4015a1b96d Mon Sep 17 00:00:00 2001 From: Phil Pluckthun Date: Fri, 24 Apr 2020 17:19:11 +0100 Subject: [PATCH] Split up optimistic result flush logic to two streams --- exchanges/graphcache/src/cacheExchange.ts | 52 ++++++++++++----------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/exchanges/graphcache/src/cacheExchange.ts b/exchanges/graphcache/src/cacheExchange.ts index ab1f27fdfa..f80b5985db 100644 --- a/exchanges/graphcache/src/cacheExchange.ts +++ b/exchanges/graphcache/src/cacheExchange.ts @@ -17,7 +17,6 @@ import { share, fromPromise, fromArray, - fromValue, buffer, take, mergeMap, @@ -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 => { - 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$, + ]); }; };