Angular 6 view not updating, even with ChangeDetectorRef, ngZone, and requestAnimationFrame

Viewed 474

In my component.ts, I have a loop that converts WAV audio data to MP3:

for (var i = 0; i < samples.length; i += sampleBlockSize) {

  let sampleChunk = samples.subarray(i, i + sampleBlockSize);
  var mp3buf = mp3encoder.encodeBuffer(sampleChunk);
  if (mp3buf.length > 0) {
      mp3Data.push(mp3buf);
  }

  this.convertedPercent = Math.floor( ( i / samples.length ) * 100);
  console.log('convertedPercent: ' + this.convertedPercent);
}

console.log('This is where the HTML view jumps from 0% to 100%');

In my component.html I have code that displays what percentage of the audio has been converted so far:

<p>Conversion is {{ convertedPercent }}% complete</p>

While the conversion is happening, it logs the correct conversion percentage to the console in real time, however the view stays stuck at 0% complete. Once the loop ends, it instantly jumps to 100%.

I have tried:

  • this.cd.detectChanges();
  • wrapping the line which changes the value of convertedPercent in zone.run()
  • wrapping the line which changes the value of convertedPercent in requestAnimationFrame()

What on Earth should I try next?

1 Answers

As we know, Javascript is Single Threaded. If you perform heavy computation, your main thread will be blocked and won't be freed until it completes. May be you can try with Observables, with is async operation browser will process it based on priority.

Component:

convertedPercent$ = new Subject<any>();
convertedPercent$.next(this.convertedPercent);

Template:

<p>Conversion is  {{ convertedPercent$ | async }}% complete</p>
Related