Home > Mobile >  I want to create a function that observes a property then calls a function once the property reaches
I want to create a function that observes a property then calls a function once the property reaches

Time:05-16

My goal is to refresh the view once the percentageChages() reaches 100:

The value:

  this.uploadPercent = task.percentageChanges(); 

The function I want to create :

refreshView(){
Once this.uploadPercent == 100;
  window.location.reload();
}

A standrad loop seemed too resource intesive for this, something light would be nice.

CodePudding user response:

You could make use of rxjs and Observables (comes built in with angular).

For instance instantiate uploadPecent to be:

uploadPercent = new BehaviorSubject<number>(0);

Then you can set the value of this similarly to before with:

uploadPercent.next(task.percentageChanges());

Then all you have to do is set up pipeline like so (could do this inside the ngOnInit lifecycle hook):

this.uploadPercent.pipe(
  takeUntil(this.destroy$)
).subscribe(x => {
  if (x >= 100) {
    window.location.reload();
  }
});

Where destroy$ is instantiated to:

destroy$ = new Subject<void>();

And the destroy pattern is completed in ngOnDestroy (this prevents memory leaks from the subscription):

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

You can find out more about rxjs from the official docs here: https://rxjs.dev/guide/overview Or this website is also good for info: https://www.learnrxjs.io/

  • Related