Skip to content

Instantly share code, notes, and snippets.

@westonpace
Created May 24, 2017 15:47
Show Gist options
  • Save westonpace/213e0398da2f70d38bdf15593f74199d to your computer and use it in GitHub Desktop.
Save westonpace/213e0398da2f70d38bdf15593f74199d to your computer and use it in GitHub Desktop.
Example showing the pitfalls of using an observable for init code
import { Observable, Observer } from 'rxjs';
function runTest(share: boolean, delay: boolean) {
let observable = Observable.create((observer: Observer<boolean>) => {
setTimeout(() => {
console.log('I did my expensive thingy');
observer.next(true);
}, 1000);
});
if(share) {
observable = observable.shareReplay(1);
}
observable.first().subscribe(() => {
console.log('Sub 1 done');
});
if(delay) {
setTimeout(() => {
observable.first().subscribe(() => {
console.log('Delayed sub done');
});
}, 2000);
} else {
observable.first().subscribe(() => {
console.log('Sub 2 done');
});
}
return observable.first().toPromise();
};
console.log('==No sharing==');
runTest(false, false).then(() => {
console.log('==Sharing==');
return runTest(true, false);
}).then(() => {
console.log('==Sharing but delayed==');
return runTest(true, true);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment