Created
May 24, 2017 15:47
-
-
Save westonpace/213e0398da2f70d38bdf15593f74199d to your computer and use it in GitHub Desktop.
Example showing the pitfalls of using an observable for init code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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