Skip to content

Pass synchronous observable to isLoadingService.add() - isLoading doesn't cancel as expected

Under certain conditions, an api call may return a synchronous observable, such as of([]), rather than accessing a backend service. If you pass the function of(), (which returns an observable synchronously), to isLoadingService.add() the loading indicator is set but never cancels. Note that if you make of() asynchronous, by using the scheduled function, and pass that to isLoadingService, then isLoadingService cancels the isLoading indicator (on the next event turn) as expected.

TEST 1

import { IsLoadingService } from '@service-work/is-loading';
import { of } from 'rxjs';

const isLoadingService = new IsLoadingService();

/* synchronous observable */
isLoadingService.add(of(['testValue']));

/* isLoading: true - expected? */
console.log('isLoading: ' + isLoadingService.isLoading()); // isLoading: true

/* try remove isLoading indicator */
isLoadingService.remove();

/* isLoading: true - expected? */
console.log('isLoading: ' + isLoadingService.isLoading()); // isLoading: true

/* wait a turn /
setTimeout(() => {
/
isLoading: true - expected? */
console.log('isLoading: ' + isLoadingService.isLoading()); // isLoading: true

/* try remove isLoading indicator */
isLoadingService.remove();

/* isLoading: true - expected? */
console.log('isLoading: ' + isLoadingService.isLoading()); // isLoading: true

}, 0);

Console output

isLoading: true
isLoading: true
isLoading: true
isLoading: true

TEST 2

import { IsLoadingService } from '@service-work/is-loading';
import { scheduled, asapScheduler } from 'rxjs';

const isLoadingService = new IsLoadingService();

/* asynchronous observable */
isLoadingService.add(scheduled(of(['testValue']), asapScheduler));

/* isLoading: true as expected */
console.log('isLoading: ' + isLoadingService.isLoading()); // isLoading: true

setTimeout(() => {
/* isLoading: false as isLoadingService removes the isLoading indicator following take(1) from the observable */
console.log('isLoading: ' + isLoadingService.isLoading()); // isLoading: false
}, 0);

Console output:

isLoading: true
isLoading: false