how to get latest emitted value from a observable #6887
Replies: 1 comment
-
I think that there are ways already available for your use case, although the best way depends on the details. On the other hand I think it might be useful to know that in your example the reason why the output is function answer() { return 42; } produces a single value. Calling this function twice will produce the same value. The same is true for takeFourNumbers.pipe(first()).subscribe(v=>console.log(v,'actual get')) what you're doing is to start producing the values as "defined" by how Going back to your original question, there are several options now that depend on your use case. ImperativelyI'd use this option when you're in an imperative use case where you need to have the latest value. The simplest way would be to just store the last emitted value takeFourNumbers.subscribe(x => {
...
latestValue = x;
}); or using the takeFourNumbers.pipe(
tap(x => { latestValue = x; })
).subscribe(x => {...}); ReactivelyYou have several options here based on how you want to combine mouseclicks$.pipe(
withLatestFrom(takeFourNumbers)
).subscribe(([mouseClick, latestNumber]) => {...}) share/replayYou could also adapt the Observable to emit the latest value on subscription using const takeFourNumbers = numbers.pipe(shareReplay(1), take(4)); There are some caveats though to BehaviorSubject / ReplaySubjectA Either way, in your example you would need connect your const subject = new ReplaySubject(1); // No initial value and we're only interested in the latest
const numbers = interval(1000);
const takeFourNumbers = numbers.pipe(take(4));
takeFourNumbers.subscribe(subject); // connects the Observable and the subject
subject.subscribe(x => console.log('Next: ', x));
setTimeout(()=>{
console.log('how can we get the latest value which is 1?');
subject.pipe(first()).subscribe(v=>console.log(v,'actual get'))
},2500) I hope that this is of any help to you! |
Beta Was this translation helpful? Give feedback.
-
As the demo shows, as the title said, how to get the latest emitted value from an observable?
In my case, I just want to get the latest value and do a one-time job. How can I do it?
Maybe we can have an operator like
takeLatest()
orlatest()
?Beta Was this translation helpful? Give feedback.
All reactions