Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[observable] Add publishReplay operator #121

Merged
merged 1 commit into from
Aug 18, 2017

Conversation

bjoerge
Copy link
Member

@bjoerge bjoerge commented Aug 18, 2017

This operator in combination with refCount() is super useful when we want to share a value represented by a single underlying resource between multiple subscribers.

Pseudo-ish example:

const snapshots = new Observable(observer => {
  // will be called when first observer subscribes
  const connection = server.listen('someDocument', currentSnapshot => {
    observer.next(currentSnapshot)
  })
  return () => {
    // will be called when last subscriber unsubscribes
    connection.close()
  }
})
.publishReplay(1)
.refCount()

const first = snapshots.subscribe(snapshot => console.log(snapshot))

// later
const second = snapshots.subscribe(snapshot => console.log(snapshot))

Here, both subscribers will immediately receive the most recent snapshot, but only one connection to the server will be kept open (for as long as there are subscribers). When the last subscriber unsubscribes, the connection will be closed. (and if someone subscribes again later, the connection will be re-established again).

@bjoerge bjoerge requested a review from rexxars August 18, 2017 14:01
@rexxars
Copy link
Member

rexxars commented Aug 18, 2017

LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants