I need to implement HTTP Longpolling using rxjs (in an Angular environment). The challenge is that I need to change the request parameters on every call. To be more specific: I need to change the from/to values to have it rolling. For example always go back 1 minute in time from the current time.
Right now I have the following implementation:
const requestParameter$ = new BehaviorSubject<MetricAggregationParams>(initialRequestParameter);
this.metricsService
.searchAggregatedMetrics(requestParameter$)
.pipe(
tap((metricInstancesResult) => {
// do something with the result
}),
delay(3000),
tap(() => {
requestParameter$.next({
...requestParameter$.value,
from: DateTime.now()
.minus({ minutes: timerange.timerangeInMinutes as number })
.toISO(),
to: DateTime.now().toISO()
});
})
)
.subscribe();
})
searchAggregatedMetrics(requestParameter$: BehaviorSubject<MetricAggregationParamsDto>) {
return requestParameter$.pipe(
concatMap((requestParameter) =>
this.http.post<MetricAggregationResult>(`REST_URL`, requestParameter)
)
);
}
Here are some constraints:
- The first request should start right away (no delay)
- The next request should start after the previous request has finished + 3000ms
Is there a way to have the longpolling logic all together in the searchAggregatedMetrics method?
If I understand the problem right, you are facing some kind of recursive problem. Recursion in rxJs is addressed with the
expandoperator.One solution to your problem could be along these lines
There is clearly a repetition in the above code, which can therefore coded a bit more elegantly (but maybe less clearly) like this
Here a stackblitz that reproduces this solution