subscribe function doesn't work correctly

你离开我真会死。 提交于 2019-12-14 03:34:55

问题


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.



来源:https://stackoverflow.com/questions/45847183/subscribe-function-doesnt-work-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!