I'm attempting to achieve a specific functionality using RxJS:
- Trigger an event
- Make an API call
- Upon receiving the API response, do one of the following:
- Wait for at least X milliseconds after triggering the event
- If X milliseconds have already passed since triggering the event, return immediately
This feature is valuable for enhancing user experience, as it ensures that a loading icon is displayed for a minimum duration even if the API call is swift.
So far, I have not been able to implement this using delay
, throttle
, debounce
, or any similar methods.
this.triggeredEvent
.switchMap(data => {
let startTime = Date.now();
return this.invokeApiService(data)
.delay(new Date(startTime + 1000));
})
I initially thought this approach would work, but using an absolute date seems to calculate the time difference from the current time rather than scheduling the delay for that exact time.
UPDATE:
It appears there isn't a pre-built operator that functions according to my requirements. Therefore, I designed a custom solution as I anticipate using it extensively in my project:
import { Observable } from "rxjs/Observable";
function delayAtLeast<T>(this: Observable<T>, delay: number): Observable<T> {
return Observable.combineLatest(
Observable.timer(delay),
this)
.map(([_, i]) => i);
}
Observable.prototype.delayAtLeast = delayAtLeast;
declare module "rxjs/Observable" {
interface Observable<T> {
delayAtLeast: typeof delayAtLeast;
}
}