简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM