Skip to content

Instantly share code, notes, and snippets.

@gm50x
Created September 25, 2020 12:24
Show Gist options
  • Save gm50x/4001621e5cd949495b7a6e208f7012f7 to your computer and use it in GitHub Desktop.
Save gm50x/4001621e5cd949495b7a6e208f7012f7 to your computer and use it in GitHub Desktop.
/************************************************************
* *
* ObservablesOne *
* Simples example of playing with rxjs-observables *
* *
* reqruiements: npm install rxjs *
* *
************************************************************/
/**
* AS ALWAYS, Import the observables
*/
const { Observable } = require('rxjs')
/**
* Methods to make things run slower
* So that we, humans, can understand what's going on
*/
const sleep = (ms = 1000) => {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, ms)
})
}
sleepSeconds = (seconds = 1) => sleep(seconds * 1000)
/**
* Get your observable stream, manually
*/
const getObservable$ = () => new Observable(
async subscriber => {
subscriber.next('H')
await sleep(500)
subscriber.next('e')
await sleep(500)
subscriber.next('l')
await sleep(500)
subscriber.next('l')
await sleep(500)
subscriber.next('o')
await sleep(500)
subscriber.next(' ')
await sleep(500)
subscriber.next('W')
await sleep(500)
subscriber.next('o')
await sleep(500)
subscriber.next('r')
await sleep(500)
subscriber.next('l')
await sleep(500)
subscriber.next('d')
await sleep(500)
subscriber.next('!')
await sleep(500)
subscriber.complete()
})
/**
* Helper method to process each chunk
* Here, we want to print on the same
* line and push whatever came in into
* an array
*/
const processNext$ = (next, stream) => {
process.stdout.write(`[${next}]`)
stream.push(next)
}
/**
*
* Main process
* Gets an observable stream and process it
*/
const main = async () => {
const obs$ = getObservable$()
const stream = []
const subs$ = obs$.subscribe({
next: (x) => processNext$(x, stream),
error: (err) => console.error(err.message),
complete: () => { console.log(`\nCompleted: ${stream.join('')}`) }
})
console.log(`>>> Subscription is ${subs$.closed ? 'CLOSED' : 'OPEN'}<<<`)
await sleepSeconds(10)
console.log(`>>> Subscription is ${subs$.closed ? 'CLOSED' : 'OPEN'}<<<`)
}
/**
* Expected output from the main process
* [H]>>> Subscription is OPEN<<<
* [e][l][l][o][ ][W][o][r][l][d][!]
* Completed: Hello World!
* >>> Subscription is CLOSED<<<
*/
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment