Skip to content

Commit

Permalink
feat(router): observables in lifecycle
Browse files Browse the repository at this point in the history
Given that Observables are moving through committee to become a web
standard, it would be of use to support that standard similarly to how
Promises are supported.

Like with promises, if an observable (really, anything with a subscribe
function) is returned from the activate lifecycle event, the router will
wait until there's data present before finishing the routing process.
  • Loading branch information
Ixonal committed Apr 29, 2016
1 parent cf88671 commit 38bcad5
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/activation.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,40 @@ function shouldContinue(output, router: Router) {
return output;
}

class SafeSubscription {
//if this were TypeScript, subscriptionFunc would be of type
//(sub: SafeSubscription) => Subscription
constructor(subscriptionFunc) {
this._subscribed = true;
this._subscription = subscriptionFunc(this);

if(!this._subscribed) this.unsubscribe()
}

unsubscribe() {
if(this._subscription) this._subscription.unsubscribe();

this._subscribed = false;
}
}

function processPotential(obj, resolve, reject) {
if (obj && typeof obj.then === 'function') {
return Promise.resolve(obj).then(resolve).catch(reject);
}

if(obj && typeof obj.subscribe === 'function') {
//an object with a subscribe function should be assumed to be an observable
new SafeSubscription(sub => obj.subscribe({
next() {
sub.unsubscribe();
resolve(obj);
},
error(err) {
reject(err);
}
}));
}

try {
return resolve(obj);
Expand Down

0 comments on commit 38bcad5

Please sign in to comment.