Skip to content

Instantly share code, notes, and snippets.

@baflo
Created July 3, 2020 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baflo/9b617fc88da895882b4676b86629962f to your computer and use it in GitHub Desktop.
Save baflo/9b617fc88da895882b4676b86629962f to your computer and use it in GitHub Desktop.
Buffering requests to the same resource
class Requester {
/** Intermediate observable used to prepare fetching connector identifiers and updating `connectorIdentifiers$`. */
protected readonly fetchConnectorIdentifiers$ = new Subject<number>();
constructor() {
/**
* When idle and an identifiers fetch request comes in, this waits 100ms before triggering.
* When just received a value (within the 100ms window), these do not increase the window timeout.
*/
const fetchConnectorIdentifiersTimer$ = this.fetchConnectorIdentifiers$.pipe(mapTo(undefined), auditTime(100));
/**
* Buffers identifier fetch requests for the time given by the `fetchConnectorIdentifiersTimer$`, then fetches
* all requested identifiers at once. This must be done, as many labels possibly request the UUID concurrently.
*/
this.fetchConnectorIdentifiers$.pipe(bufferWhen(() => fetchConnectorIdentifiersTimer$)).subscribe(async connectorIds => {
await this.immediateUpdateConnectorUuidsByIds(connectorIds);
});
}
/**
* Fetches the identifiers for the given connector ID, i.e. an object of both the ID and the UUID,
* then updates `connectorIdentifiers$` with the new values. The update is buffered and the effect
* can be observed with `getConnectorUuidById`.
*/
public updateConnectorUuidById(connectorId: number) {
if (connectorId > -1) {
this.fetchConnectorIdentifiers$.next(connectorId);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment