Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

Smarter Tokens fetching #3546

Merged
merged 13 commits into from
Nov 23, 2016
27 changes: 24 additions & 3 deletions js/src/api/contract/contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export default class Contract {
this._instance[fn.signature] = fn;
});

this._sendSubscriptionChanges();
this._subscribedToChanges = false;
this._subscribedToChangesId = null;
}

get address () {
Expand Down Expand Up @@ -271,12 +272,14 @@ export default class Contract {
.getFilterLogs(filterId)
.then((logs) => {
callback(null, this.parseEventLogs(logs));

this._subscriptions[subscriptionId] = {
options,
callback,
filterId
};

this._subscribeToChanges();
return subscriptionId;
});
});
Expand All @@ -287,12 +290,30 @@ export default class Contract {
.uninstallFilter(this._subscriptions[subscriptionId].filterId)
.then(() => {
delete this._subscriptions[subscriptionId];

if (Object.keys(this._subscriptions).length === 0) {
this._unsubscribeToChanges();
}
})
.catch((error) => {
console.error('unsubscribe', error);
});
}

_subscribeToChanges = () => {
if (this._subscribedToChanges) {
return;
}

this._subscribedToChanges = true;
this._sendSubscriptionChanges();
}

_unsubscribeToChanges = () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

unsubscribeFromChanges? (;

this._subscribedToChanges = false;
clearTimeout(this._subscribedToChangesId);
}

_sendSubscriptionChanges = () => {
const subscriptions = Object.values(this._subscriptions);
const timeout = () => setTimeout(this._sendSubscriptionChanges, 1000);
Expand All @@ -316,11 +337,11 @@ export default class Contract {
}
});

timeout();
this._subscribedToChangesId = timeout();
})
.catch((error) => {
console.error('_sendSubscriptionChanges', error);
timeout();
this._subscribedToChangesId = timeout();
});
}
}