Skip to content

Commit

Permalink
perf(refuges): cache get refuges/
Browse files Browse the repository at this point in the history
If we return the same observable and we share it, then we'll only have
to do one petition for N subscribers. Right now we're doing N petitions
for N subscribers
  • Loading branch information
Pablito2020 committed Oct 24, 2023
1 parent 9c1697d commit ed2f70e
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions app/src/app/services/refuge/refuge.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import {catchError, distinctUntilChanged, map, mergeMap, Observable, ObservableInput, of, retry, timer} from 'rxjs';
import {
catchError,
distinctUntilChanged,
map,
mergeMap,
Observable,
ObservableInput,
of,
retry,
share,
timer
} from 'rxjs';
import {GetAllRefugesErrors, GetAllRefugesResponse,} from '../../schemas/refuge/get-all-refuges-schema';
import {environment} from '../../../environments/environment';
import {isValidId, Refuge, RefugePattern} from '../../schemas/refuge/refuge';
Expand All @@ -12,17 +23,21 @@ import {DeleteRefugeFromIdErrors, DeleteRefugeResponse,} from '../../schemas/ref
providedIn: 'root',
})
export class RefugeService {
private getRefugesConnection?: Observable<GetAllRefugesResponse>

constructor(private http: HttpClient) {
}

/**
* @description get refuges from the API every 3 seconds
*/
getRefuges(): Observable<GetAllRefugesResponse> {
return timer(0, 3000).pipe(
mergeMap(() => this.getAllRefugesFromApi()),
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))
);
if (!this.getRefugesConnection) {
this.getRefugesConnection = timer(0, 3_000).pipe(
mergeMap(() => this.getAllRefugesFromApi()),
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
).pipe(
share()
);
}
return this.getRefugesConnection;
}

getRefugeFrom(id: string): Observable<GetRefugeResponse> {
Expand Down

0 comments on commit ed2f70e

Please sign in to comment.