I have implemented a simple BehaviorSubject
,
import {BehaviorSubject} from "rxjs";
class MyWeirdoClass {
constructor() {}
private st: Subject<boolean> = new BehaviorSubject<boolean>(null);
changeSt(val:boolean){
this.st.next(val);
}
val(){
this.st.subscribe(res=>{
if (res){
console.log(res);
}
})
}
stStatus() {
this.val();
this.changeSt(true);
this.val();
this.changeSt(false);
this.val();
}
}
now when running stStatus()
gives logs the following output on the console.
true
true
while I expect the value
false
true
false
What is wrong with my implementation?
The output you're getting is correct:
this.val();
This just makes the first subscription which doesn't print anything thanks to if (res) {...}
.
this.changeSt(true);
Set's the value to true
which is printed by the first subscription.
this.val();
Makes the second subscription which prints the second true
.
this.changeSt(false);
You set it to false
which is ignored by all subscribers because of if (res) {...}
.
this.val();
The same as above.
because these lines:
if (res){
console.log(res);
}
the value only gets logged whenever it is truthy.
btw, you misunderstanding the way your code work.
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