subscribe function doesn't work correctly

2019-09-21 13:57发布

问题:

in this piece of code the subscribe function executes after the last line in loadFromDB function:

  loadFromDB(){
    const loading = this.loadingCtrl.create({
      content: 'pleas wait'
    });
    loading.present();
    this.getInterviewFromDB()
      .subscribe((data) => {
        this.events = data;
        console.log( 'before');
      });
    this.getMeetingsFromDB().subscribe((data)=>{
      this.events.concat(data);
    });
    loading.dismiss();

    console.log( 'after');
  }

the loading is present and dismiss before loading any data from database and this is the output of the log

illustrates that line under the subscribe function Execute after the console.log inside it ...can any body explain to me .. ?!

回答1:

This makes perfectly sense. You are subscribing to asynchronous steams. You cant expect them to finish in order. If you want them to finish at the same time you can do something like this:

Observable.forkJoin(this.getInterviewFromDB(), this.getMeetingsFromDB())
    .subscribe(res => {
       let interviews = res[0];
       let meetings = res[1];
    })


回答2:

This is the way callbacks work. subscribe takes a callback function as an argument. I suggest you learn what callbacks are and how they work before continuing.

Here is a little bit of information on how subscribe works: ReactiveX subscribe function

Robin provides a good solution in his answer with forkJoin. forkJoin joins the values emitted by multiple Observables into an array and creates a new Observable. You can then subscribe to this Observable, just like Robin did in his example, to get the array value which is the first argument of the callback.