Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented a fix for the setTimeout unsubscribe thing #1567

Merged
merged 7 commits into from
Apr 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/core/ObservableQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,37 @@ export class ObservableQuery<T> extends Observable<ApolloQueryResult<T>> {
}

public result(): Promise<ApolloQueryResult<T>> {
const that = this;
return new Promise((resolve, reject) => {
const subscription = this.subscribe({
let subscription: (Subscription | null) = null;
const observer: Observer<ApolloQueryResult<T>> = {
next(result) {
resolve(result);

// Stop the query within the QueryManager if we can before
// this function returns.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should add more comments about why we need this.

//
// We do this in order to prevent observers piling up within
// the QueryManager. Notice that we only fully unsubscribe
// from the subscription in a setTimeout(..., 0) call. This call can
// actually be handled by the browser at a much later time. If queries
// are fired in the meantime, observers that should have been removed
// from the QueryManager will continue to fire, causing an unnecessary
// performance hit.
const selectedObservers = that.observers.filter((obs: Observer<ApolloQueryResult<T>>) => obs !== observer);
if (selectedObservers.length === 0) {
that.queryManager.removeQuery(that.queryId);
}

setTimeout(() => {
subscription.unsubscribe();
(subscription as Subscription).unsubscribe();
}, 0);
},
error(error) {
reject(error);
},
});
};
subscription = that.subscribe(observer);
});
}

Expand Down
8 changes: 6 additions & 2 deletions src/core/QueryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -884,11 +884,15 @@ export class QueryManager {
});
}

public removeQuery(queryId: string) {
delete this.queryListeners[queryId];
delete this.queryDocuments[queryId];
}

public stopQuery(queryId: string) {
// XXX in the future if we should cancel the request
// so that it never tries to return data
delete this.queryListeners[queryId];
delete this.queryDocuments[queryId];
this.removeQuery(queryId);
this.stopQueryInStore(queryId);
}

Expand Down