'How do I get the last value from a ReplaySubject?
Below is a snippet that describes what I'm trying to do. In my application I have a replaysubject that's used throughout. At a certain point I want to get the last value emitted from the subject, but last
doesn't seem to work on a ReplaySubject.
const subject = new Rx.ReplaySubject();
subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);
subject.subscribe(num => console.log(num));
var lastObserver = subject.last();
lastObserver.subscribe(num => console.log('last: ' + num));
The code above doesn't fire anything for the lastObserver
, but subscribe works just fine.
Solution 1:[1]
Maybe your confusion is about how the .last()
operator is supposed to work?
.last()
should wait for a stream to complete, then give you the last value emitted before the stream ended. So in order for it to work, the stream will need to end.
I believe your lastObserver
will emit as soon as the subject completes.
const subject = new Rx.ReplaySubject();
subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);
subject.subscribe(num => console.log(num));
subject.complete(); // end your stream here
var lastObserver = subject.last();
lastObserver.subscribe(num => console.log('last: ' + num));
If you don't want your stream to end, but you do want subscribers to receive the last value emitted before subscription, consider reaching for BehaviorSubject
, which was designed for this use case.
Solution 2:[2]
I do like this:
debounce
ignores all happened before and leaves the last one
const subject = new Rx.ReplaySubject();
subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);
subject
.pipe(debounceTime(0), take(1))
.subscribe(num => console.log('last: ' + num));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | xtianjohns |
Solution 2 |