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

460
Visualizações
Rxjs: how to get latest emitted value from a observable

As the demo shows, as the title said

const { combineLatest, interval, of } = rxjs;
const { first, last, sample, take, withLatestFrom } = rxjs.operators;

const numbers = interval(1000);

const takeFourNumbers = numbers.pipe(take(4));
takeFourNumbers.subscribe(x => console.log('Next: ', x));
setTimeout(()=>{
 console.log('how can we get the latest value which is 1?');
 takeFourNumbers.pipe(first()).subscribe(v=>console.log(v,'actual get'))
},2500)
// Logs:
// Next: 0
// Next: 1
// how can we get the latest value which is 1?
// Next: 2
// 0 actual get
// Next: 3
<script src="https://cdn.jsdelivr.net/npm/rxjs@7.5.5/dist/bundles/rxjs.umd.js"></script>

In my case, I just want to get the latest value and do a one-time job. How can I do it?

I am thinking if we have an operator like takeLatest() or latest()? But I didn't find anyone.

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

0

The problem boils down to sharing provider(data source) or "Hot vs Cold" observables, you want the latest value to be shared across different subscriptions so you basically want a hot observable, Observable returned from interval operator is cold so you need to make it hot and doing so is quite simple:

const takeFourNumbers = numbers.pipe(take(4), shareReplay(1));

now it doesn't matter how many times you subscribe to it, all subscribers will share the value

edit: my bad, it should be shareReplay so that it gives you last emitted value as soon as you subscribe to it so now you should get 1 from that subscription inside setTimeout

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