Display loader only when api call will be longer then 1 sec

116 Views Asked by At

I have tried and I still trying to create a mechanism in Angular using rx that will display my loader, but only if the API call is longer than 1 second, if it is shorter I would not like to display it.

I've tried many different ways, but I haven't been able to achieve what I need.

The closest I came to a solution was in this case:

        const apiCall = this.searchService
            .query(this.query)
            .pipe(finalize(()=> this.loading = false));

        timer(1000)
            .pipe(takeUntil(apiCall))
            .subscribe(()=> {
                this.loading = true;
            })

        apiCall.subscribe(result => {
            //do smth
        })

In this case loader would be shown after the API request was completed, but it would immediately disappear becouse of finalize method (and it would also be called twice).

Does anyone have an idea on how to do something like this because I'm running out of ideas?

1

There are 1 best solutions below

0
On BEST ANSWER

I haven't tested your code but my guess is your code will call the api twice and thats the reason it removes the loader on the first call and second call doesn't care about the loader at all. something like this should work.

const apiObservable = this.searchService.
  .query(this.query).pipe(startWith(null));

const isLoadingObservable = timer(1000).pipe(
  map(() => true),
  startWith(false),
  take(2),
);

combineLatest(apiObservable, isLoadingObservable).pipe(
     tap(([resp, isLoading]) => this.isLoading = isLoading),
     filter(([resp, isLoading]) => resp !== null)
).subscribe(resp => {
  this.isLoading = false;
  //do smth
});