使用 rxjs 来限制回调 [英] Using rxjs to throttle a callback
问题描述
我正在使用一个 API,我在其中注册了一个频繁发生的回调.
I am consuming an API in which I register a callback that occurs frequently.
function myCallback(event) {
// do things with event, something computationally intensive
}
const something = createSomething({
onSomethingHappened: myCallback
})
我想限制触发此回调的速率,可能使用 throttle.该项目使用捆绑了 rx 的 Angular.如何调整我的代码,以便 myCallback
使用 rx 将其限制在 300 毫秒?
I'd like to limit the rate at which this callback fires, probably using throttle. This project uses Angular which bundles rx. How can I adapt my code so myCallback
it throttled at 300ms using rx?
我对 observables 的工作原理有一个基本的了解,但弄清楚回调接口如何转换为 observable 接口有点令人困惑.
I have a basic grasp on how observables work but it's been a bit confusing to figure out how the callback interface would convert to observable interface.
(随着答案的出现而编辑)
(edited as answers come)
推荐答案
我认为你可以使用 fromEventPattern
:
let something;
const src$ = fromEventPattern(
handler => (something = createSomething({ onSomethingHappened: handler })),
);
src$.pipe(
throttleTime(300),
map(args => myCallback(args))
);
注意:这里假设 myCallback
是一个同步操作.
Note: this assumed that myCallback
is a synchronous operation.
传递给 fromEventPattern
的第一个参数是 addHandler
.它还可以有 removeHandler
,您可以在其中放置您的拆卸逻辑(例如:从内存中释放、清除值等).
The first argument passed to fromEventPattern
is the addHandler
. It can also have the removeHandler
, where you can put your teardown logic(e.g: releasing from memory, nulling out values etc).
为了更好地理解什么是 handler
以及为什么在那里使用它,让我们看看 fromEventPattern
是如何实现的:
In order to get a better understanding of what is handler
and why is it used there, let's see how fromEventPattern
is implemented:
return new Observable<T | T[]>(subscriber => {
const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);
let retValue: any;
try {
retValue = addHandler(handler);
} catch (err) {
subscriber.error(err);
return undefined;
}
if (!isFunction(removeHandler)) {
return undefined;
}
// This returned function will be called when the observable
// is unsubscribed. That is, on manual unsubscription, on complete, or on error.
return () => removeHandler(handler, retValue) ;
});
来源.
如你所见,通过 handler
,你可以让返回的 observable 在需要发出一些东西的时候.
As you can see, through handler
, you can let the returned observable when it's time to emit something.
这篇关于使用 rxjs 来限制回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!