Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.0 kB
6
Indexable
Never
@Injectable()
export class RxStore {
    readonly remove$ = new Subject<string>();
    readonly edit$ = new Subject<M>();
    readonly add$ = new Subject<M>();
    readonly refresh$ = new BehaviorSubject<null>(null);
    private onCloseMethod!: () => void;
    private readonly items$ = this.initItems();
    private readonly removal$ = this.remove$.pipe(wrap(id => this.itemService.delete(id)));
    private readonly edital$ = this.edit$.pipe(
        wrap(obj => this.itemService.edit(obj.id, obj)),
        tap(() => {
            if (this.onCloseMethod) {
                this.onCloseMethod();
            }
        })
    );
    private readonly addition$ = this.add$.pipe(
        wrap(obj => this.itemService.create(obj)),
        tap(() => {
            if (this.onCloseMethod) {
                this.onCloseMethod();
            }
        })
    );
    readonly elements$ = this.items$.pipe(
        filter(Boolean),
        exhaustMap(items =>
            combineLatest([this.addition$, this.removal$, this.edital$]).pipe(
                scan((result, [add, remove, edit]) => {
                    return (add ? result.concat(add) : result)
                        .filter((item: M) => item?.id !== remove)
                        .map((item: M) => {
                            return item?.id === edit?.id ? edit : item;
                        });
                }, items),
                startWith(items)
            )
        ),
        shareReplay(1)
    );
    readonly loading$ = loading([this.add$, this.remove$, this.edit$, this.refresh$], [this.items$, this.elements$]);

    constructor(private itemService: ItemService) {}

    public setOnCloseMethod(onClose: () => void): void {
        this.onCloseMethod = onClose;
    }

    private initItems() {
        return this.refresh$.pipe(
            exhaustMap(() => this.itemService.getAll().pipe(catchError(() => of(null)))),
            share()
        );
    }
}
Leave a Comment