Skip to content

Instantly share code, notes, and snippets.

@2color
Last active January 10, 2019 16:05
Show Gist options
  • Save 2color/5f1594a465672a63ba4fa9eccfeec01b to your computer and use it in GitHub Desktop.
Save 2color/5f1594a465672a63ba4fa9eccfeec01b to your computer and use it in GitHub Desktop.
Example of how publishReplay works
// https://jsbin.com/gacexawuju/edit?js,console
//emit value every 1 second
const source = Rx.Observable.interval(1000).take(5);
const example = source
//side effects will be executed once
.do(() => console.log('Do Something!'))
//do nothing until connect() is called
// Cache the last 3 values
.publishReplay(3)
/*
source will not emit values until connect() is called
output: (after 2s)
"Do Something!"
"Subscriber One: 0"
"Do Something!"
"Subscriber One: 1"
"Do Something!"
"Subscriber One: 2"
"Do Something!"
"Subscriber One: 3"
"Do Something!"
"Subscriber One: 4"
"Subscriber Two: 2"
"Subscriber Two: 3"
"Subscriber Two: 4"
*/
const subscribe = example.subscribe(val => console.log(`Subscriber One: ${val}`));
//call connect after 5 seconds, causing source to begin emitting items
setTimeout(() => {
example.connect();
},2000)
setTimeout(() => {
example.subscribe(val => console.log(`Subscriber Two: ${val}`));
},7500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment