2
votes

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!

2
simply use plain old subject ? This supplies you with next() still. - Chund
Oh bother... Thank you! I believe this is what I'm looking for. For some reason I didn't think Subject had the next() method to trigger changes and didn't even try =P - mottosson
The big difference between a subject and a behavior subject is the behavior subject stores the last emitted value and new subscribers get the last emitted on subscribing. With a subject new subscribers don't get a value until the next time it emits. - Adrian Brand
Thanks @AdrianBrand for the explanation! - mottosson

2 Answers

3
votes

I think there are several options:

  • Use Subject
  • Keep BehaviorSubject, but pipe with with skip(1) to ignore the first value
0
votes

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