private setupService()

in pathology/viewer/src/services/cohort.service.ts [85:158]


  private setupService() {
    if (!this.cohortsEnabled) return;
    this.userService.getCurrentUser$().subscribe((currentUser) => {
      this.currentUser = currentUser ?? '';
    });
    this.loading$.next(true);

    // Updates selectedCohortIsReadOnly based on current user and
    // selectedPathologyCohort
    combineLatest([
      this.userService.getCurrentUser$(),
      this.selectedPathologyCohort$,
    ])
        .pipe(
            takeUntil(this.destroyed$),
            tap(([currentUser, selectedPathologyCohort]) => {
              if (currentUser && selectedPathologyCohort) {
                const foundUser =
                    (selectedPathologyCohort.userAccess ??
                     []).find(({userEmail}) => userEmail === currentUser);

                const isUserReadOnly: boolean = foundUser?.accessRole ===
                    'PATHOLOGY_USER_ACCESS_ROLE_VIEWER';
                this.selectedCohortIsReadOnly$.next(isUserReadOnly);
              } else {
                this.selectedCohortIsReadOnly$.next(true);
              }
            }))
        .subscribe();

    // Combined loading state for page.
    combineLatest([
      this.loadingCohortInfos$,
      this.loadingSelectedPathologyCohort$,
      this.loadingSelectedPathologyCohortCases$,
    ])
        .pipe(
            takeUntil(this.destroyed$),
            tap((mergedLoading) => {
              const allLoading =
                  mergedLoading.some((loading) => loading === true);
              this.loading$.next(allLoading);
            }),
            )
        .subscribe();

    this.selectedPathologyCohort$
        .pipe(
            // Update selectedCohortInfo to match selectedPathologyCohort.
            tap((selectedPathologyCohort) => {
              const isSelectedCohortInfoSame: boolean =
                  (this.selectedCohortInfo$.getValue() &&
                   this.selectedCohortInfo$.getValue()?.name ===
                       selectedPathologyCohort?.name) ??
                  false;

              if (!isSelectedCohortInfoSame && selectedPathologyCohort) {
                this.selectedCohortInfo$.next(
                    this.pathologyCohortToCohortInfo(selectedPathologyCohort));
              }
            }),
            // Fetch cases
            switchMap((selectedPathologyCohort) => {
              if (selectedPathologyCohort) {
                this.selectedPathologyCohortCases$.next([]);
                return this.fetchPathologyCohortCases(selectedPathologyCohort);
              }
              return of(undefined);
            }),
            finalize(() => {
              this.loadingSelectedPathologyCohort$.next(false);
            }))
        .subscribe();
  }