0

My Angular 4 Service:

@Injectable()
export class MyService {

  private myArray: string[] = [];

  constructor() { }

  private calculate(result): void {
    myArray.length = 0;
    // Do some calculations and add results in myArray
  }

  public invokeCallBack(callBack: Function) {
    // the function callBack returns an observable
    // Rest calls are done in the callBack function
    callBack().subscribe(
      (result) => {
        // Rest call is finished
        this.calculate(result);
      }
    );
  }
}

Other components call invokeCallBack(callBack) many times.

What will happen, if 2 (or more) rest calls are finished at the same time?

1) Will the method this.calculate(result) be called 2 times simultaneously? If that's the case, it could be possible that myArray has an inconsistent state, because 2 calculations take place at the same time (=> race condition). How could this problem be solved?

2) Or will this.calculate(result) always be called synchronous? If that's the case, only one calculation can take place at a time and therefore myArray is always (guaranteed) in a consistent state.

Fabian
  • 106
  • 1
  • 7

1 Answers1

3

Assuming there's no asynchronous code in calculate, the method will always run to completion before being called again.

It's not possible for 2 separate "instances" of calculate to run simultaneously.

This is because JavaScript (in browsers) is single-threaded.

Cerbrus
  • 60,471
  • 15
  • 115
  • 132