Is it safe to subscribe to an observable with an async function

泄露秘密 提交于 2020-01-17 01:49:24

问题


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:

  1. 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.
  2. 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:

  1. It will not wait for one iteration of handleUpdatedValuesComingFromSensor to finish before starting another (assuming handleUpdatedValuesComingFromSensor truly does something asynchronous) so you could have multiple instances of handleUpdatedValuesComingFromSensor in flight at the same time.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!