hamobi
hamobi

Reputation: 8130

Variable in my view wont reflect value from observable

I've checked out a lot of examples on SO on how to solve this issue but none of the solutions are working for me. I have a class running a process recursively 20 times and I'm keeping track of the process in an observable. I want to use those values to create a progress bar on the view.

I know the observable is working because if I subscribe directly in my component and console.log the numbers they are appearing in 20 increments as expected.

No matter what I do I'm only seeing the initial value and the final value in my view. I am not able to see the progress.

Any advice here?

// my scheduler class
private calendarPercent = new Subject()
private finishedCalendarMax = 20
private finishedCalendarCount = 0

// this stuff is called recursively until we hit our finishedCalendarMax
this.finishedCalendarCount++
this.calendarPercent.next(this.finishedCalendarCount / this.finishedCalendarMax)

// get my observable
getFinishedCalendarPercent() {
    return this.calendarPercent
}


// in app.component.ts i create my scheduler class
public scheduler = new Scheduler()


// in app.component.html
{{ scheduler.getFinishedCalendarPercent()  | async }}

Upvotes: 2

Views: 106

Answers (1)

user184994
user184994

Reputation: 18281

When you call this.generateCalendar recursively, simply wrap it in a setTimeout, like so:

setTimeout(() => this.generateCalendar(), 0)

With the timeout set to 0, this moves the next calculation to the end of the execution queue, which gives the UI a chance to render the changes.

Here is a StackBlitz demo

Upvotes: 2

Related Questions