I’m completely new to rxjs and trying to accomplish one task – essentially I need a Promise-like API with the following differences:
- Unlike the standard
Promise
my API should be able toresolve
multiple times. - When calling
await
/then
the last resolved value should be used. - If my API was never resolved the
await
/then
should hung up, just like the standardPromise
. - Additionally I need a
reset
method which will be resetting my API object so the followingawait
/then
calls will hung up like in the point 3.
How can I implement the needed behaviour? I think rxjs Observable
and lastValueFrom
is what I need, but I just can’t figure out how to use it.
Pseudocode example usage:
const myAuthObservable = new MyObservableApi<Auth>((resolve) =>
subscribe(
(s) => s.auth,
(auth) => {
if (auth) {
resolve(auth); // this can be called multiple times
}
}
)
);
emitter.on("start", async () => {
// always the last auth will be returned
// or the api will hung up until the first auth is emitted
const auth = await myAuthObservable;
myAuthObservable.reset();
});
2
Answers
after reading @Barmar comment I eventually came up with a simple non-rxjs solution
usage:
I believe I have what you’re looking for – a custom subject that behaves like a single buffer ReplaySubject, but can be reset. This code has been adapted from that exact class to provide the functionality you seek.
StackBlitz
In the example below, the subscription will emit all values, but the promises created from firstValueFrom will only emit if the subject has a value and reset hasn’t cleared the cached value.
Your usage would be like the example below. Whatever sets myAuthObservable will have to make sure Auth isn’t undefined, or you could update the ResettableSubject class to ignore undefined values passed to the next method.