Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS BehaviorSubject without initial value on subscribe

Tags:

angular

rxjs

I have an Angular application where I use RxJS BehaviorSubject to subscribe to a bool value that indicates an "in progress" status.

But I'm only interested in when the state changes and not the current state on subscription.

export class ProgressService {
  private InProgress$ = new BehaviorSubject<boolean>(false);

  constructor() {}

  public getInProgressStateSubject() {
    return this.InProgress$;
  }
}

...

this.progressService.getInProgressSubject().subscribe((inProgress: boolean) => {

  // This will be triggered in the moment of subscription as well as on state chages

  if (inProgress) {
    // Toggle on state
  } else {
    // Toggle off state
  }
});

I like how it works, I just don't want it to trigger on subscription.

Are there any other similar operators in RxJS that can help me, or can I do it in any other way?

Thanks!

like image 575
mottosson Avatar asked Feb 11 '26 09:02

mottosson


2 Answers

I think there are several options:

  • Use Subject
  • Keep BehaviorSubject, but pipe with with skip(1) to ignore the first value
like image 91
MoxxiManagarm Avatar answered Feb 12 '26 21:02

MoxxiManagarm


You can use ReplaySubject with bufferSize 1 and they only have 1 value and the last.

like image 27
JORGE ROJAS Avatar answered Feb 12 '26 23:02

JORGE ROJAS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!