Skip to content

Instantly share code, notes, and snippets.

@dfreeman
Created April 10, 2018 20:18
Show Gist options
  • Save dfreeman/e5c125122adf4e73f4c9e1bf993da2da to your computer and use it in GitHub Desktop.
Save dfreeman/e5c125122adf4e73f4c9e1bf993da2da to your computer and use it in GitHub Desktop.
backoff-polling
import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';
export default Ember.Controller.extend({
pollModelWithCustomStuff: task(function*() {
let poller = backoffPoller(() => model.reload());
while (get(model, 'isRunning')) {
// Do custom stuff before polling
yield poller.poll();
// Do custom stuff after polling
}
// Do stuff after it's done
}),
pollModelWithoutFancyStuff: task(function*() {
yield backoffPoller(() => model.reload())
.pollUntil(() => !get(model, 'isRunning'));
// Do stuff after it's done
}),
});
function backoffPoller(callback, options) {
return BackoffPoller.create({ callback, ...options });
}
const BackoffPoller = Ember.Object.extend({
baseInterval: 250,
maxInterval: 60 * 1000,
retryCount: 0,
callback: null,
poll() {
return this.get('_poll').perform(...arguments);
},
pollUntil() {
return this.get('_pollUntil').perform(...arguments);
},
_poll: task(function*() {
const { retryCount, baseInterval, maxInterval, callback } = this;
this.incrementProperty('retryCount');
if (retryCount > 0) {
yield timeout(Math.min(baseInterval, baseInterval * Math.pow(1.25, retryCount - 1)));
}
return callback();
}),
_pollUntil: task(function*(condition) {
while (!(yield condition())) {
yield this.poll();
}
}),
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
<br>
<br>
{
"version": "0.13.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.16.2",
"ember-template-compiler": "2.16.2",
"ember-testing": "2.16.2"
},
"addons": {
"ember-concurrency": "*"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment