In my application, there is a service layer that manages data and delivers it to components with the same value.
When the value of isProcessed
is false, I need to send requests to the API. The service will make 10 attempts every half a second.
If the requests fail during the attempts, only 3 more requests will be made.
Once isProcessed
becomes true, all pending requests should stop.
The logic for this functionality is already implemented, but I am facing an issue where I cannot output the last observable value received. All responses are being sent instead.
Requests are being made using observables, whether the value is false or true, but I am interested in capturing only the last response.
https://i.sstatic.net/mJjQh.png
All responses from requests are being received by the component, not just the last one
This is the service responsible for accessing the API:
public getPositionConsolidate(): Observable<PosicaoConsolidada> {
return this.http.get<PosicaoConsolidada>(`${environment.api.basePosicaoConsolidada}/consolidado`)
.pipe(
map(res => res),
retryWhen(genericRetryStrategy()),
shareReplay(1),
catchError(err => {
console.log('Error in Position Consolidate', err);
return throwError(err);
})
)
}
This is the service responsible for managing data and delivering it to the component:
public positionConsolidate() {
let subject = new BehaviorSubject<any>([]);
this.api.getPositionConsolidate().subscribe(response => {
if(response.hasProcessado == false) {
for (let numberRequest = 0; numberRequest < 10; numberRequest++) {
setTimeout(() => {
//subject.next(this.api.getPosicaoConsolidada().subscribe());
this.api.getPositionConsolidate().subscribe(res => {
subject.next(res)
})
}, numberRequest * 500, numberRequest);
}
} else {
retryWhen(genericRetryStrategy()),
finalize(() => this.loadingService.loadingOff())
}
})
return subject.asObservable()
}
In the component:
public ngOnInit() {
this.coreState.positionConsolidate().subscribe(res => console.log(res))
}