简体   繁体   中英

How do I wait for an observable to update before executing more code?

I think an observable may not be the right thing to use here but I'm not sure what else I could use to provide live updates of a variable's value to another class.

I have this loop in a service class

elements.forEach(element => {
  doStuff();
  this.numberSubject.next(valueFromDoStuff);
})

and a subscription to the observable in my component class

numberSubjectObservable.subscribe(result => {
  this.value = result
}

What I want is to be able to pause the loop until my Angular component is updated with the newest value from the subscription but right now it waits until the end before rendering the final value.

Not sure I understand exactly what you are trying to do here but if you need to wait on this.value to equal the numberSubjectObservable result you can use an async method and try the following

you can change this

numberSubjectObservable.subscribe(result => {
  this.value = result
}

to this

this.value = await numberSubjectObservable.toPromise();

Not sure if your doStuff() is sync or async. In case it is sync, you don't see any updates in your progress bar, because the change has happened instantaneously, so that you only see the final value.

In case it is async, first of all you have to forget about forEach, it [does not work with it] .

I've prepared a demo for you. The first button triggers synchronous iteration. The second button triggers an async iteration.

Faking an async doStuff:

private async asyncDoStuff(element: number): Promise<number>{
  console.log('running async doStuff with element: ' + element);
  return new Promise(resolve => {
   setTimeout(resolve, 1000);
  }).then(()=>{return this.doStuff(element);});
}

And looping through your array to see the updates with a 1 sec delay:

public async asyncIterate(){
  let newElement = 0;
  for (const element of this.elements){
  newElement = await this.asyncDoStuff(element);
  console.log('newElement: ' + newElement);
  this.numberAsyncSubject.next(newElement);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM