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$, + ]); }; };