Skip to content

Instantly share code, notes, and snippets.

@mtelesborges
Last active October 17, 2023 00:32
Show Gist options
  • Save mtelesborges/56b427290dcb78f63c0ea3a26e4a2d06 to your computer and use it in GitHub Desktop.
Save mtelesborges/56b427290dcb78f63c0ea3a26e4a2d06 to your computer and use it in GitHub Desktop.
Angular Polling Service
import { Inject, Injectable, InjectionToken } from '@angular/core';
import { Observable, combineLatest, filter, interval, take, takeWhile } from 'rxjs';
// REQUEST_INTEVAL and MAX_QUANTITY_ATTEMPTS are InjectionToken
// InjectionTokens can be configured globally at the module, component or service level only once
// defines a interval in seconds to api request
export const REQUEST_INTEVAL = new InjectionToken<number>('REQUEST_INTEVAL', {
providedIn: 'root',
factory: () => 2000
});
// defines a max quantity of attempts
// if the api not responds with a successful response in the max quantity of attempts, the service stop the requests
export const MAX_QUANTITY_ATTEMPTS = new InjectionToken<number>('MAX_QUANTITY_ATTEMPTS', {
providedIn: 'root',
factory: () => 10
});
@Injectable({ providedIn: 'root' })
export class PoollingService {
constructor(
@Inject(REQUEST_INTEVAL) private requestInterval: number,
@Inject(MAX_QUANTITY_ATTEMPTS) private maxQuantityAttempts: number
) {}
poll<T>(observable$: Observable<T>) {
return combineLatest([observable$.pipe(take(1)), interval(this.requestInterval)]).pipe(
take(this.maxQuantityAttempts),
takeWhile(
response => /* Adds the condition to stop the service */,
true
),
filter(response => /* Adds the condition for not emit values for subscription */)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment