Skip to content

Instantly share code, notes, and snippets.

@Klowner
Created July 24, 2020 17:52
Show Gist options
  • Save Klowner/c4b4b1220fbc0f649481296db967d801 to your computer and use it in GitHub Desktop.
Save Klowner/c4b4b1220fbc0f649481296db967d801 to your computer and use it in GitHub Desktop.
type NewProjectRecord = Omit<Partial<ProjectRecord>, 'id'>;
type DeletableProjectRecord = Pick<ProjectRecord, 'id'>;
export class ProjectsContext {
constructor(private service: ProjectService) {}
private readonly remoteRefresh$ = new BehaviorSubject<void>(null);
private readonly create$ = new Subject<NewProjectRecord>();
private readonly delete$ = new Subject<DeletableProjectRecord>();
private readonly remoteProjects$ = this.remoteRefresh$.pipe(
switchMap(() => this.service.listProjects()),
shareReplay(1),
);
private readonly remoteProjectCreated$ = this.create$.pipe(
concatMap((params) => this.service.createProject(params)),
);
private readonly collectionWithCreatedProject$: Observable<ProjectRecord[]> =
this.remoteProjectCreated$.pipe(
mergeMap((newProject) => this.projects$.pipe(
take(1),
map((currentProjects) => [...currentProjects, newProject]),
),
));
private readonly remoteProjectDeleted$ = this.delete$.pipe(
concatMap((params) => this.service.deleteProject(params).pipe(
catchError(() => EMPTY),
)),
);
private readonly collectionWithoutDeletedProject$: Observable<ProjectRecord[]> =
this.remoteProjectDeleted$.pipe(
concatMap((deletedProject) => this.projects$.pipe(
take(1),
map((projects) => projects.filter((p) => p.id != deletedProject.id)),
)),
);
public readonly projects$ = merge(
this.remoteProjects$,
this.collectionWithCreatedProject$,
this.collectionWithoutDeletedProject$,
).pipe(
shareReplay(1),
);
public remoteRefresh(): Observable<ProjectRecord[]> {
this.remoteRefresh$.next();
return this.projects$;
}
public create(project: NewProjectRecord): void {
this.create$.next(project);
}
public delete(project: DeletableProjectRecord): void {
this.delete$.next(project);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment