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?

All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111

2 Answers2

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.

martin
  • 93,354
  • 25
  • 191
  • 226
  • 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? – Alexander Mar 18 '23 at 14:05
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.

Yvonne Aburrow
  • 2,602
  • 1
  • 17
  • 47
Tiep Phan
  • 12,386
  • 3
  • 38
  • 41