BehaviorSubject with boolean value is not working as intended
Asked Answered
L

2

7

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?

Limoli answered 31/1, 2017 at 7:8 Comment(0)
C
5

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.

Cylix answered 31/1, 2017 at 7:19 Comment(1)
I'm trying to make manual map reload via reload$, which for some reason does not work: this.reload$.pipe(filter(reload => reload === true), tap(reload => reload = false)).subscribe([Map API request]). Even though the value DOES change to false, next time I set reload$ to true externally, it shows that it IS still true, so the triggering does not happen. Don't understand why is that. This does not work either: this.reload$.pipe(filter(reload => reload === true), tap(() => reload$.next(false))).subscribe([Map API request]). What am I doing wrong here?Ra
L
2

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.

Locally answered 31/1, 2017 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.