Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BehaviorSubject with boolean value is not working as intended

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?

like image 344
All Іѕ Vаиітy Avatar asked Jan 31 '17 07:01

All Іѕ Vаиітy


2 Answers

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.

like image 95
martin Avatar answered Nov 08 '22 08:11

martin


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.

like image 2
Tiep Phan Avatar answered Nov 08 '22 06:11

Tiep Phan