BehaviorSubject with boolean value is not working as intended

All Іѕ Vаиітy picture All Іѕ Vаиітy · Jan 31, 2017 · Viewed 7.7k times · Source

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?

Answer

martin picture martin · Jan 31, 2017

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.