Last active
February 10, 2023 22:42
-
-
Save roman-bgonz/0ac7e4d330a3c39475090485adaa09d2 to your computer and use it in GitHub Desktop.
Demo to show promises vs observables (Use Code Runner Extension on VSCode)
This file contains hidden or 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
const { Observable } = require('rxjs'); | |
const { filter } = require('rxjs/operators'); | |
/** | |
* PROMISE | |
*/ | |
// A promise can only return a single value | |
const promesa = () => { | |
return new Promise((resolve, reject) => { | |
// Async process is simulated | |
setTimeout(() => { | |
resolve('Promesa 1'); | |
}, 1000); | |
}); | |
}; | |
// We gave an async context to a fuction which will call itself | |
(async () => { | |
const rta = await promesa(); | |
console.log(rta); | |
})(); | |
/** | |
* OBSERVABLE | |
*/ | |
// While an observable can emmit multiple values | |
const obs = () => { | |
return new Observable((observer) => { | |
// After 1 second, the first value is emmited | |
setTimeout(() => { | |
observer.next('Observable 1'); | |
}, 1000); | |
// 1 second later, the second value is emmited | |
setTimeout(() => { | |
observer.next('Observable 2'); | |
}, 2000); | |
// If we complete the observable, even if we send a new value, it will not be sent | |
setTimeout(() => { | |
observer.complete(); // Completes | |
observer.next('Observable 3'); // This will not be sent | |
}, 3000); | |
}); | |
}; | |
(() => { | |
const observ$ = obs(); | |
observ$.subscribe({ | |
next: (val) => console.log(val), | |
}); | |
})(); | |
const obsPair = () => { | |
return new Observable((observer) => { | |
setTimeout(() => { | |
observer.next(2); | |
observer.next(3); | |
observer.next(5); | |
observer.next(7); | |
observer.next(8); | |
observer.next(10); | |
observer.next(4); | |
observer.next(20); | |
observer.complete(); | |
}, 4000); | |
}); | |
}; | |
(() => { | |
const observ2$ = obsPair(); | |
observ2$ | |
.pipe( | |
// Here we stablish that we are going to be subscribed only when value is a pair number | |
filter((v) => v % 2 === 0) | |
) | |
.subscribe({ | |
next: (val) => console.log(val), | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment