Skip to content

Instantly share code, notes, and snippets.

@liuwenzhuang
Created December 8, 2020 03:36
Show Gist options
  • Save liuwenzhuang/10497f24514d35a20379ec6b63c0ebe9 to your computer and use it in GitHub Desktop.
Save liuwenzhuang/10497f24514d35a20379ec6b63c0ebe9 to your computer and use it in GitHub Desktop.
rxjs loading indicator with delay opening and close immediately, open observable will be cancel if request time less than 300ms
import { iif, of, Subject } from 'rxjs';
import { switchMap, delay, finalize } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
const loadingSubject = new Subject<boolean>();
const loading$ = loadingSubject.pipe(
switchMap(flag => {
return iif(
() => flag,
of(flag).pipe(delay(300)),
of(flag)
)
})
)
const loadingElem = document.getElementById('loading-elem')
loading$.subscribe(flag => {
loadingElem.style.display = flag ? 'block' : 'none'
})
loadingSubject.next(true) // open loading with 300ms delay
ajax('/api/get/users/list').pipe(
finalize(() => {
loadingSubject.next(false) // close loading immediately, open loading observable will be cancel if request time less than 300ms
})
).subscribe(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment