Skip to content

Instantly share code, notes, and snippets.

@benlesh
Last active August 23, 2017 00:54
Show Gist options
  • Save benlesh/06154a6f730e43380d243347aeae1c49 to your computer and use it in GitHub Desktop.
Save benlesh/06154a6f730e43380d243347aeae1c49 to your computer and use it in GitHub Desktop.
// An observable that emits 10 multiples of 100 every 1 second
const source$ = Observable.interval(1000)
.take(10)
.map(x => x * 100);
/**
* returns a promise that waits `ms` milliseconds and emits "done"
*/
function promiseDelay(ms) {
return new Promise(resolve => {
setTimeout(() => resolve('done'), ms);
});
}
// using it in a switchMap
source$.switchMap(x => promiseDelay(x)) // works
.subscribe(x => console.log(x));
source$.switchMap(promiseDelay) // just a little more terse
.subscribe(x => console.log(x));
// or takeUntil
source$.takeUntil(doAsyncThing('hi')) // totally works
.subscribe(x => console.log(x))
// or weird stuff you want to do like
Observable.of(promiseDelay(100), promiseDelay(10000)).mergeAll()
.subscribe(x => console.log(x))
function getErroringPromise() {
console.log('getErroringPromise called');
return Promise.reject(new Error('sad'));
}
Observable.defer(getErroringPromise)
.retry(3)
.subscribe(x => console.log);
// logs "getErroringPromise called" 4 times (once + 3 retries), then errors
Observable.defer(async function() {
const a = await Promise.resolve(1);
const b = a + await Promise.resolve(2);
return a + b + await Promise.resolve(3);
})
.subscribe(x => console.log(x)) // logs "7"
const button = document.querySelector('button');
const click$ = Observable.fromEvent(button, 'click');
/**
* Waits for 10 clicks of the button
* then posts a timestamp of the tenth click to an endpoint
* using fetch
*/
async function doWork() {
await click$.take(10)
.map((_, i) => i + 1)
.forEach(n => console.log(`click ${n}`));
return await fetch(
'notify/tenclicks',
{ method: 'POST', body: Date.now() }
);
}
doWork();
const source$ = Observable.interval(1000).take(3); // emits 0, 1, 2
// waits 3 seconds, then logs "2".
// because the observable takes 3 seconds to complete, and
// the interval emits incremented numbers starting at 0
async function test() {
console.log(await source$.toPromise());
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment