Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show LoadingController for multiple requests in Ionic 2

As per the Ionic documentation I could load Ionic LoadingController using this piece of code:

ionViewLoaded() {
  let loader = this.loading.create({
    content: 'Getting latest entries...',
  });

  loader.present().then(() => {
    this.someService.getLatestEntries()
      .subscribe(res => {
        this.latestEntries = res;
        loader.dismiss();
      });

  });
}

This works fine if I am just making 1 ajax request. But I have 5 requests to be made and if I hide / show loading controller like this it leads to flickering of the screens.

Is there a way where I can present the loadingController but then dismiss() only when all of the Ajax requests have been completed?

EDIT: Requests do not depend upon one another. They are independent. What I am looking for is a way to get notified when all observable's request is completed. That way I could dismiss the LoadingController when all of them complete.

like image 963
Tim Liberty Avatar asked Feb 05 '23 11:02

Tim Liberty


2 Answers

I'm using following utility in my app. This would also work for multiple steps or/and pages if we want to show the same loader and need to change loader text at different steps.

We can call showLoader() multiple times, would need to ultimately call hideLoader().

@Injectable()
export class Utility {
    loader: any = null;
    constructor(private _alertCtrl: AlertController,
        private _loadingController: LoadingController) {
    }

    private showLoadingHandler(message) {
        if (this.loader == null) {
            this.loader = this._loadingController.create({
                content: message
            });
            this.loader.present();
        } else {
            this.loader.data.content = message;
        }
    }

    private hideLoadingHandler() {
        if (this.loader != null) {
            this.loader.dismiss();
            this.loader = null;
        }
    }

    public showLoader(message) {
        this.showLoadingHandler(message);
    }

    public hideLoader() {
        this.hideLoadingHandler();
    }
}   
like image 103
Sandeep Sharma Avatar answered Apr 12 '23 23:04

Sandeep Sharma


You should not use multiple subscribe, and if your requests do not depend on each other you can use the combineLatest operator, so all requests will execute concurently, and get notified when they have all completed :

ionViewLoaded() {
  let loader = this.loading.create({
    content: 'Getting latest entries...',
  });
  let loaded = Observable.combineLatest(
    this.someService.getLastEntries().do((entries) => {
      //do stuff with last entries
    }),
    this.someOtherServices.getOtherStuff().do((stuff) => {
      // do stuff with stuff
    })
    // etc...
  )
  loader.present().then(() => loaded.toPromise()).then(() => loader.dismiss());
}
like image 25
n00dl3 Avatar answered Apr 13 '23 01:04

n00dl3