Skip to content

Instantly share code, notes, and snippets.

@2color

2color/publishReplay.js

Last active Jan 10, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.