From 4f97c7e2830331788c80a8d14719fec3578cc739 Mon Sep 17 00:00:00 2001 From: Matt Gibson Date: Wed, 27 Sep 2023 17:33:01 -0400 Subject: [PATCH] Establish account service observables and update methods --- .../src/auth/services/account.service.ts | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/libs/common/src/auth/services/account.service.ts b/libs/common/src/auth/services/account.service.ts index 8079b16e2d..735c9a69f2 100644 --- a/libs/common/src/auth/services/account.service.ts +++ b/libs/common/src/auth/services/account.service.ts @@ -1,4 +1,11 @@ -import { BehaviorSubject, Subject } from "rxjs"; +import { + BehaviorSubject, + Subject, + combineLatestWith, + map, + distinctUntilChanged, + share, +} from "rxjs"; import { InternalAccountService } from "../../auth/abstractions/account.service"; import { LogService } from "../../platform/abstractions/log.service"; @@ -8,20 +15,27 @@ import { AuthenticationStatus } from "../enums/authentication-status"; export class AccountServiceImplementation implements InternalAccountService { private accounts = new BehaviorSubject>({}); - private activeAccount = new BehaviorSubject<{ - id: UserId | undefined; - status: AuthenticationStatus | undefined; - }>({ id: undefined, status: undefined }); + private activeAccountId = new BehaviorSubject(undefined); private lock = new Subject(); private logout = new Subject(); accounts$ = this.accounts.asObservable(); - activeAccount$ = this.activeAccount.asObservable(); + activeAccount$ = this.activeAccountId.pipe( + combineLatestWith(this.accounts$), + map(([id, accounts]) => (id ? { id, status: accounts[id] } : undefined)), + distinctUntilChanged((a, b) => a.id === b.id && a.status === b.status), + share() + ); accountLock$ = this.lock.asObservable(); accountLogout$ = this.logout.asObservable(); constructor(private messagingService: MessagingService, private logService: LogService) {} setAccountStatus(userId: UserId, status: AuthenticationStatus): void { + if (this.accounts.value[userId] === status) { + // Do not emit on no change + return; + } + this.accounts.value[userId] = status; this.accounts.next(this.accounts.value); if (status === AuthenticationStatus.LoggedOut) { @@ -32,9 +46,15 @@ export class AccountServiceImplementation implements InternalAccountService { } switchAccount(userId: UserId) { - if (this.accounts.value[userId] != null) { + if (userId == null) { + // indicates no account is active + this.activeAccountId.next(undefined); + } + + if (this.accounts.value[userId] == null) { throw new Error("Account does not exist"); } + this.activeAccountId.next(userId); } // TODO: update to use our own account status settings.