Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
How to keep shareReplay alive when there are no subscribers?

I need to share a hot Observable between multiple subscribers and emit the latest value to new subscribers. I am trying to achieve this with shareReplay(1), however, the first subscriber fails to retrieve the latest value because the shareReplay operator doesn't do anything when there is no subscription, so it doesn't store anything for the first subscriber.

How do I fix this without having a permanent subscription just to keep shareReplay alive?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can solve your problem using publishReplay(1) instead of shareReplay(1):

const subject = new Subject()

const source$ = subject.pipe(publishReplay(1))
source$.connect();

subject.next(1)
subject.next(2)
subject.next(3)
source$.subscribe(v => console.log(v))
subject.next(4)
subject.next(5)
subject.next(6)

Output:

3
4
5
6

The important part is that with publishReplay, you can control when the subscription starts (source$.connect()). shareReplay will start only with the first subscription.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda