0
votes

I am writing an application using reactivex and typescript that controls a charging battery. I use a lot of promises here, which takes me to my question: I want a promise inside a chain to be resolved as soon as a variable (state of charge) reaches a certain value.

I tried using a while loop that checks the value periodically and returns as soon as it is reached, but this blocks the whole program.

private _performChargeJob(job: ChargeJob): Promise<any> {
    // Return a promise that is resolved if the job has finished processing.
    return this._performGoal(job.goals[0].goalId)
        .then(() => {
            this._handleCharge(this._soc, 100); // this is the important part where I'd wish the promise to resolve
        }).then(() => {
            this.logConsole("Finished charging.");
            this.callRosService({name: "set_charge_state", serviceType: "insystems_srvs/SetChargeState"}, {
                set_charge_state: 0,                 // stop charging
            });
        });
}

private _handleCharge(soc: number, maxSoc: number) {
// this function should return/resolve a promise when variable soc reaches 100.0
    this.logConsole("starting charge.");
    this.callRosService({name: "set_charge_state", serviceType: "insystems_srvs/SetChargeState"}, {
        set_charge_state: 1,                // start charging
    });
}

Here, I expect some kind of watch() (which is deprecated) or new promise that could wait for the value to reach that level. Maybe even an observable?

Thanks!

Use a getter/setter on that variable or observe the variable in some other way, whatever reactiveX gives you for this. A while loop is usually not a good solution to fix async issues, it's equivalent to polling. - Shilly
I found skipWhile for observables in reactiveX and will try that. - mneumann
Is it the RxJS implementation that you use? Since reactivex seems to be for multiple languages with different syntax. - Shilly
Yes, I use RxJS. I am using this framework in particular, which uses observables a lot. Unfortunately, in my case, the promise in this chain is only thennable and catchable and does not support observable functions. - mneumann
Can't you observe the this._soc variable alone and then use the .subscribe() method coaty gives you to resolve the promise? - Shilly