Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { Resource } from '@ngxp/rest';
import { Observable, map, withLatestFrom } from 'rxjs';
import { StateResource } from '../resource/resource.util';
import { ApiSingleResourceStateService } from './state.service';
export class ApiStateServiceExecuter<B extends Resource, T extends Resource> {
private stateService: ApiSingleResourceStateService<B, T>;
private baseResource: Observable<StateResource<T>>;
shouldExecute: boolean;
public static init<B extends Resource, T extends Resource>(
stateService: ApiSingleResourceStateService<B, T>,
): ApiStateServiceExecuter<B, T> {
return new ApiStateServiceExecuter<B, T>(stateService);
}
constructor(stateService: ApiSingleResourceStateService<B, T>) {
this.stateService = stateService;
this.shouldExecute = true;
}
public withBaseResource(baseResource: Observable<StateResource<T>>): this {
this.baseResource = baseResource;
return this;
}
public execute(runnable: (resource: T) => void): Observable<StateResource<T>> {
return this.baseResource.pipe(
withLatestFrom(this.stateService.selectResource()),
map(([baseStateResource, stateResource]) => {
if (this.shouldExecute && !baseStateResource.loading) {
runnable(stateResource.resource);
this.shouldExecute = false;
return { ...baseStateResource, loading: true };
}
return baseStateResource;
}),
);
}
}