I have an rxjs ReplaySubject that will either emit a value or null depending on what environment I am on. Meaning if in a certain environment I make a service call and get the data. If I am not in that environment I just call next(null) on the replay subject. In the component where I subscribe to this all works fine if the service call was made. If I had done next(null) then my callback is never fired.
My assumption is that the null value will not be returned because it was set before I subscribed but I thought that was the entire point of ReplaySubject. I have googled then until I ran out of different ways to explain the issue and all I get is the read me file for ReplaySubject. Hoping somebody can tell me what I am doing wrong. I thought maybe it was because I passed in null so I passed in "Hello" instead and still nothing. Here is a code sample:
public Data = new ReplaySubject<any>(1);
init(){
if(!window.Something){
//subscribe callback is never fired in this case.
this.Data.next(null);
}else{
this.http.get(...).map(...{
//this works
this.Data.next(result);
});
}}
The mistake I made actually had nothing to do with Rx. I can't remember exactly but it was making so the condition was never true. This kept the code from executing.
Using .next(null)
on any Observable is correct. Everything is a value in RxJS including null
and undefined
. So the problem is probably somewhere else than this.
This is what you're doing right now and it both cases (when you uncomment the second if
) it works as should. The value is stored in the ReplaySubject
and then replayed or pushed directly to the current observer:
let subject = new ReplaySubject(1);
// if (!window.document) {
if (!window.whatever) {
subject.next(null);
} else {
setTimeout(() => {
subject.next('Hello');
}, 500);
}
subject.subscribe(val => console.log(val));
See live demo: https://jsbin.com/cigocak/edit?js,console
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With