Mia loha.dev
Mia loha.dev

Reputation: 581

How to return a value using the previous and the current value of a BehaviorSubject?

In my angular app, I have a user service, an activeUser$ behaviorSubject and a loggedIn$ one which will be true or false based(piped(mapped)) on the value of activeUser$. When loggedIn$’s next value is true and then false, that would mean that the user has logged out. There is a function which I want to trigger only when it is true and then false. A loggedOut$ observable as a result would be awesome! Any idea?

Upvotes: 0

Views: 1356

Answers (2)

Mia loha.dev
Mia loha.dev

Reputation: 581

Just found out the answer I needed from here

I have implemented it like this:

loggedOut$ = this.loggedIn$.pipe(
    distinctUntilChanged(),
    map((current) => !current)
);

Upvotes: 1

Anton Marinenko
Anton Marinenko

Reputation: 2992

Learn more about pairwise operator here

In your case the code would be like this:

    loggedOut$ = this.loggedIn$.pipe(
      pairwise(),
      filter(([previous, current]) => previous && !current)
    ).subscribe(...)

Upvotes: 2

Related Questions