Skip to content

Commit

Permalink
Polling-based live queries in Relay
Browse files Browse the repository at this point in the history
Reviewed By: josephsavona

Differential Revision: D4554519

fbshipit-source-id: 0775ebbcf75c39f852bc96af1cac8e709e7427cb
  • Loading branch information
laneyk authored and facebook-github-bot committed Apr 12, 2017
1 parent 0871b67 commit 88d09dc
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
Expand Up @@ -22,9 +22,12 @@ import type {
*
* - `force`: causes a query to be issued unconditionally, irrespective of the
* state of any configured response cache.
* - `poll`: causes a query to live update by polling at the specified interval
in milliseconds. (This value will be passed to setTimeout.)
*/
export type CacheConfig = {
force: boolean,
force?: ?boolean,
poll?: ?number,
};

/**
Expand Down
48 changes: 48 additions & 0 deletions packages/relay-runtime/network/RelayNetwork.js
Expand Up @@ -79,6 +79,17 @@ function create(
});
}

const pollInterval = cacheConfig && cacheConfig.poll;
if (pollInterval != null) {
return doFetchWithPolling(
request,
operation,
variables,
{onCompleted, onError, onNext},
pollInterval,
);
}

let isDisposed = false;
fetch(operation, variables, cacheConfig)
.then(
Expand Down Expand Up @@ -118,6 +129,43 @@ function create(
};
}

function doFetchWithPolling(
request,
operation: ConcreteBatch,
variables: Variables,
{onCompleted, onError, onNext}: Observer<RelayResponsePayload>,
pollInterval: number,
): Disposable {
invariant(
pollInterval > 0,
'RelayNetwork: Expected pollInterval to be positive, got `%s`.',
pollInterval,
);
let isDisposed = false;
let timeout = null;
const dispose = () => {
if (!isDisposed) {
isDisposed = true;
timeout && clearTimeout(timeout);
}
};
function poll() {
request(operation, variables, {force: true}).then(
payload => {
onNext && onNext(payload);
timeout = setTimeout(poll, pollInterval);
},
error => {
dispose();
onError && onError(error);
}
);
}
timeout = setTimeout(poll, pollInterval);

return {dispose};
}

function normalizePayload(
operation: ConcreteBatch,
variables: Variables,
Expand Down

0 comments on commit 88d09dc

Please sign in to comment.