问题
I have an event emitter that sends events at 50Hz. I'd like to subscribe to this emitter with an async method. The code looks like the following:
this.emitter = fromEventPattern(this.addHandler, this.removeHandler, (err, char) => [err, char]);
this.rxSubscription = this.emitter.subscribe(this.handleUpdatedValuesComingFromSensor);
and
handleUpdatedValuesComingFromSensor = async (arr: any[]): Promise<void> => {
...
await someMethodAsync();
...
}
I maybe wrong but I'm under the impression that awaiting in there makes the emitter calls onNext() immediately because I've exited the method.
This is very difficult to debug with console calls because of the event rate.
Am I right or wrong?
Thanks for your help.
EDIT 1:
I'm using typescript targetting ES2015 so a state machine is generated for async/await.
If I'm right, how can I ensure that calls do not overlap? I need to compute averages on values I receive.
回答1:
awaiting in there makes the emitter calls onNext() immediately because I've exited the method
You are correct. Rx ignores the return types of its subscription functions, so it ignores the promise returned from your async
function when it hits its first await
. This means:
- As soon as another item arrives on the observable, Rx will invoke your subscription function again. It ignored the promise that was returned, so it doesn't know the old invocation is still in progress.
- Exceptions from your
async
function will be ignored, since the promise was ignored. Some promise libraries have a global "unobserved promise error" event that can handle this.
回答2:
I'm not entirely clear what your concerns are. It is valid, your method will be called once for each and every element. It isn't going to skip anything or cut your method off halfway through but:
- It will not wait for one iteration of
handleUpdatedValuesComingFromSensor
to finish before starting another (assuminghandleUpdatedValuesComingFromSensor
truly does something asynchronous) so you could have multiple instances ofhandleUpdatedValuesComingFromSensor
in flight at the same time. - Similarly, if you have multiple subscribers then it will not wait for
handleUpdatedValuesComingFromSensor
to finish before sending the event to the next subscriber.
来源:https://stackoverflow.com/questions/55816172/is-it-safe-to-subscribe-to-an-observable-with-an-async-function