Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 42 43 44 45 46 47 48 49 50 51 52 53 54 | 1x 1x 1x 12x 6x 1x 5x 5x 5x 10x 5x 11x 10x 10x 10x 4x 4x 4x 12x 6x 1x 7x 5x 5x | import { Observable } from 'rxjs'
import { HttpResponse, QuotesV2ByIdResponse, QuoteResponseStatuses } from '@karhoo/demand-api'
export const POLLING_INTERVALS = [2000, 1000, 2000, 5000]
type QuotesAPIResponse = HttpResponse<QuotesV2ByIdResponse>
type shouldStopPollingFunc = (data: QuotesAPIResponse) => boolean
type PollFunc = () => Promise<QuotesAPIResponse>
const getPollInterval = (Iindex = 0, intervals = POLLING_INTERVALS): number => {
return intervals[index] || intervals[intervals.length - 1]
}
/**
* Polls quotes with different time intervals (2sec, 1sec, 2 sec, 5 sec)
* @param fn function to poll quotes by Id
*/
export function poll(fn: PollFunc): Observable<QuotesAPIResponse> {
let canceled = false
let count = 0
const shouldStopPolling: shouldStopPollingFunc = response =>
response.ok ? response.body.status === QuoteResponseStatuses.COMPLETED : true
return new Observable(observer => {
async function init() {
do {
try {
const response = await fn()
observer.next(response)
count += 1
if (shouldStopPolling(response)) {
observer.complete()
canceled = true
break
}
await new Promise(
// eslint-disable-next-line no-loop-func
resolve => setTimeout(resolve, getPollInterval(count))
)
} catch (err) {
observer.error(err)
}
} while (!canceled)
}
init()
return () => (canceled = true)
})
}
|