rxjs/operators#throttleTime TypeScript Examples
The following examples show how to use
rxjs/operators#throttleTime.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: sticky-header.component.ts From geonetwork-ui with GNU General Public License v2.0 | 7 votes |
ngAfterViewInit() {
this.scrollSub = fromEvent(this.scrollableParent, 'scroll', {
passive: true,
})
.pipe(
throttleTime(0, animationFrameScheduler, {
leading: true,
trailing: true,
})
)
.subscribe(this.updateSize.bind(this))
}
Example #2
Source File: canvas.component.ts From svg-path-editor with Apache License 2.0 | 6 votes |
ngOnInit(): void {
const cap = (val:number, max:number) => val > max ? max : val < -max ? -max : val;
const throttler = throttleTime(20, undefined, {leading: false, trailing: true});
this.wheel$
.pipe( buffer(this.wheel$.pipe(throttler)) )
.pipe( map(ev => ({
event: ev[0],
deltaY: ev.reduce((acc, cur) => acc + cap(cur.deltaY, 50), 0)
})))
.subscribe(this.mousewheel.bind(this));
}
Example #3
Source File: utils.tsx From ali-react-table with MIT License | 6 votes |
throttledWindowResize$ = defer(() =>
fromEvent(window, 'resize', { passive: true }).pipe(
throttleTime(150, asyncScheduler, { leading: true, trailing: true }),
),
)
Example #4
Source File: AlertService.ts From viewer-components-react with MIT License | 6 votes |
private subscribeToAlertChangesForSensor$(sensorId: string): Observable<void> {
// First, check if we need to set up a global alert triggers subscription
if (!this.alertTriggersSubscription) {
this.alertTriggersSubscription = SocketService.send$(this.socketEndpoints.subscribeAlertTriggers)
.pipe(
// tap((data: any) => LoggerService.log("Received new alert triggers:", data)),
shareReplay(0)
);
}
// Next, return an Observable that filters the global alert trigger subscription based on current sensorId
return this.alertTriggersSubscription.pipe(
filter((data: any) => {
let triggerForCurrentSensor = false;
// Status alert trigger check
if (data.entities && data.entities.includes(sensorId)) {
triggerForCurrentSensor = true;
}
// Data alert trigger check
if (data.context && !triggerForCurrentSensor) {
_forEach(data.context, (trigger: any) => {
if (trigger.sensorId === sensorId) {
triggerForCurrentSensor = true;
}
});
}
return triggerForCurrentSensor;
}),
map(() => void 0),
throttleTime(1000, undefined, {leading: true, trailing: true})
);
}
Example #5
Source File: EntityDataService.ts From viewer-components-react with MIT License | 6 votes |
// Convenience method for retrieving all relevant sensor data in one call
// Returns sensor object, alerts and last observation
public getDataForSensor$(id: string): Observable<SensorData> {
if (!this.sensorDataObservables[id]) {
this.sensorDataObservables[id] = MetricService.getMetrics$([id])
.pipe(
switchMap(() => {
return EntityService.getEntity$(EntityType.SENSOR, id)
.pipe(
switchMap((entity: any) => {
return combineLatest([
AlertService.getActiveAlertsForSensor$(id),
this.getObservationQueriesForSensor$(id)
.pipe(
switchMap((queries: ObservationQuery[]) => {
return ObservationService.getLastObservations$(entity, queries);
})
),
]).pipe(
map(([alerts, observations]: [Alert[], ObservationSet[]]) => {
return { sensor: entity, alerts, observations };
})
);
})
);
}),
throttleTime(1000, undefined, {leading: true, trailing: true}),
finalize(() => {
delete this.sensorDataObservables[id];
}),
shareReplay({
bufferSize: 1,
refCount: true,
})
);
}
return this.sensorDataObservables[id];
}
Example #6
Source File: NoticeIconView.tsx From jetlinks-ui-antd with MIT License | 6 votes |
componentDidMount() {
this.getNotice();
this.ws = getWebsocket(
`notification`,
`/notifications`,
{}
).pipe(
throttleTime(2000),
).subscribe(
(resp: any) => {
this.getNotice();
notification.open({
message: resp?.payload?.topicName,
description: resp?.payload?.message,
key: resp.payload.id,
top: 60,
btn: <Button
type="primary"
onClick={() => {
this.service
.read(resp.payload.id)
.subscribe(() => {
notification.close(resp.payload.id)
this.getNotice();
});
}}
>标记已读</Button>,
icon: <Icon type="exclamation-circle" style={{ color: '#E23D38' }} />,
});
}
);
}
Example #7
Source File: marble-test.spec.ts From s-libs with MIT License | 6 votes |
describe('marbleTest()', () => {
it('has fancy typing', () => {
staticTest(() => {
expectTypeOf(marbleTest(noop)).toEqualTypeOf<VoidFunction>();
expectTypeOf(marbleTest(async () => 1)).toEqualTypeOf<
() => Promise<number>
>();
});
});
// https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/testing/marble-testing.md
it(
'works for the first example in the docs',
marbleTest(
({ cold, expectObservable, expectSubscriptions, testScheduler }) => {
const e1 = cold(' -a--b--c---|');
const subs = ' ^----------!';
const expected = '-a-----c---|';
expectObservable(e1.pipe(throttleTime(3, testScheduler))).toBe(
expected,
);
expectSubscriptions(e1.subscriptions).toBe(subs);
},
),
);
it(
'works for two tests in a row',
marbleTest(({ cold, expectObservable }) => {
const input = ' -a-b-c|';
const expected = '-- 9ms a 9ms b 9ms (c|)';
const result = cold(input).pipe(concatMap((d) => of(d).pipe(delay(10))));
expectObservable(result).toBe(expected);
}),
);
});
Example #8
Source File: emote-search.component.ts From App with MIT License | 5 votes |
ngOnInit(): void {
scheduled([
this.form.get('query')?.valueChanges.pipe( // Look for changes to the name input form field
mergeMap((value: string) => this.selectedSearchMode.pipe(take(1), map(mode => ({ mode, value })))),
map(({ value, mode }) => ({ [mode.id]: value })) // Map SearchMode to value
) ?? EMPTY,
this.form.get('globalState')?.valueChanges.pipe( // Look for changes to the "show global"
map((value: string) => ({ globalState: value }))
) ?? EMPTY,
this.form.get('channel')?.valueChanges.pipe(
map((value: boolean) => ({ channel: value ? this.clientService.getSnapshot()?.login : '' }))
) ?? EMPTY,
this.form.get('zerowidth')?.valueChanges.pipe(
map((value: boolean) => ({ filter: {
visibility: value ? DataStructure.Emote.Visibility.ZERO_WIDTH : 0
}}))
) ?? EMPTY,
this.form.get('sortBy')?.valueChanges.pipe(
map((value: string) => ({ sortBy: value }))
) ?? EMPTY,
this.form.get('sortOrder')?.valueChanges.pipe(
map((value: RestV2.GetEmotesOptions['sortOrder']) => ({ sortOrder: value }))
) ?? EMPTY
], asyncScheduler).pipe(
mergeAll(),
map(v => this.current = { ...this.current, ...v } as any),
throttleTime(250)
).subscribe({
next: (v) => this.searchChange.next(v) // Emit the change
});
setTimeout(() => {
if (!!this.defaultSearchOptions) {
for (const k of Object.keys(this.form.getRawValue())) {
const v = (this.defaultSearchOptions as any)[k as any];
if (!v) {
continue;
}
this.form.get(k)?.patchValue(v);
}
}
}, 0);
}
Example #9
Source File: observables.ts From webapp with MIT License | 5 votes |
freshReserveBalances$ = minimalPoolBalanceReceiver$.pipe(
throttleTime(5000),
switchMapIgnoreThrow(minimalPools =>
vxm.ethBancor.getReserveBalances(minimalPools)
)
)
Example #10
Source File: ngx-hide-on-scroll.directive.ts From Elastos.Essentials.App with MIT License | 5 votes |
init() {
if (isPlatformServer(this.platformId)) {
return;
}
this.reset();
let elementToListenScrollEvent;
let scrollingElement: HTMLElement;
if (!this.scrollingElementSelector) {
elementToListenScrollEvent = window;
scrollingElement = this.getDefaultScrollingElement();
} else {
scrollingElement = document.querySelector(this.scrollingElementSelector) as HTMLElement;
if (!scrollingElement) {
console.warn(`NgxHideOnScroll: @Input() scrollingElementSelector\nElement with selector: "${this.scrollingElementSelector}" not found.`);
return;
}
elementToListenScrollEvent = scrollingElement;
}
/* elementToListenScrollEvent.addEventListener("scroll", e => {
console.log("MANUAL ON SCROLL", e)
}) */
/* elementToListenScrollEvent.addEventListener("ionScroll", e => {
console.log("MANUAL ON ION-SCROLL", e)
})
*/
const scroll$ = fromEvent<ScrollCustomEvent>(elementToListenScrollEvent, 'ionScroll').pipe(
takeUntil(this.unsubscribeNotifier),
throttleTime(50), // only emit every 50 ms
map(event => event.detail.scrollTop), // get vertical scroll position
pairwise(), // look at this and the last emitted element
// compare this and the last element to figure out scrolling direction
map(([y1, y2]): ScrollDirection => (y2 < y1 ? ScrollDirection.Up : ScrollDirection.Down)),
distinctUntilChanged(), // only emit when scrolling direction changed
share(), // share a single subscription to the underlying sequence in case of multiple subscribers
);
const scrollUp$ = scroll$.pipe(
filter(direction => direction === ScrollDirection.Up)
);
const scrollDown$ = scroll$.pipe(
filter(direction => direction === ScrollDirection.Down)
);
let scrollUpAction: () => void;
let scrollDownAction: () => void;
if (this.hideOnScroll === 'Up') {
scrollUpAction = () => this.hideElement(scrollingElement);
scrollDownAction = () => this.showElement(scrollingElement);
} else {
scrollUpAction = () => this.showElement(scrollingElement);
scrollDownAction = () => this.hideElement(scrollingElement);
}
scrollUp$.subscribe(() => {
scrollUpAction()
});
scrollDown$.subscribe(() => {
scrollDownAction()
});
}
Example #11
Source File: code-view.component.ts From nuxx with GNU Affero General Public License v3.0 | 5 votes |
ngOnInit(): void {
const importUrl = this.activatedRoute.snapshot.queryParams['import_url']
const loadRecipeUrl = this.activatedRoute.snapshot.queryParams['recipe']
if (importUrl) {
this.importUrl = importUrl
this.store.dispatch(GlobalAppConfigurationActions.OnImportMode())
this.codeRefresh()
}
if (loadRecipeUrl) {
this.recipeToLoadUuid = loadRecipeUrl
this.store.dispatch(GlobalAppConfigurationActions.OnRecipeLoadMode())
}
this.project.pipe(takeUntil(this.unSubscribe$), throttleTime(THROTTLE_TIMEOUT, undefined, { trailing: true, leading: true})).subscribe((data) => {
if (this.mode === 'compose') {
let baseVersion = Math.floor(data.version)
let versionObject = this.getVersion(baseVersion)
this.selectedSpecificVersion = versionObject
const sendData = {
name: data.name,
data: {
version: data.version,
volumes: data.volumes,
services: data.services,
networks: data.networks,
secrets: data.secrets,
configs: data.configs,
},
}
this.showSpinner = true
this.rest
.generateCode(sendData)
.pipe(takeUntil(this.unSubscribe$))
.subscribe((data: {}) => {
for (var i = 0; i < data['code'].length; ++i) {
data['code'][i] = data['code'][i].replace(/(\r\n|\n|\r)/gm, '')
}
this.code = data['code'].join('\n')
if (data['code_format']) {
this.codeFormat = data['code_format']
}
this.showSpinner = false
})
}
})
this.eventEmitterService.subscribe('load: code', (code) => {
this.code = code
})
}
Example #12
Source File: actions.ts From grafana-chinese with Apache License 2.0 | 4 votes |
runQueries = (exploreId: ExploreId): ThunkResult<void> => {
return (dispatch, getState) => {
dispatch(updateTime({ exploreId }));
const richHistory = getState().explore.richHistory;
const exploreItemState = getState().explore[exploreId];
const {
datasourceInstance,
queries,
containerWidth,
isLive: live,
range,
scanning,
queryResponse,
querySubscription,
history,
mode,
showingGraph,
showingTable,
} = exploreItemState;
if (!hasNonEmptyQuery(queries)) {
dispatch(clearQueriesAction({ exploreId }));
dispatch(stateSave()); // Remember to save to state and update location
return;
}
// Some datasource's query builders allow per-query interval limits,
// but we're using the datasource interval limit for now
const minInterval = datasourceInstance.interval;
stopQueryState(querySubscription);
const datasourceId = datasourceInstance.meta.id;
const queryOptions: QueryOptions = {
minInterval,
// maxDataPoints is used in:
// Loki - used for logs streaming for buffer size, with undefined it falls back to datasource config if it supports that.
// Elastic - limits the number of datapoints for the counts query and for logs it has hardcoded limit.
// Influx - used to correctly display logs in graph
maxDataPoints: mode === ExploreMode.Logs && datasourceId === 'loki' ? undefined : containerWidth,
liveStreaming: live,
showingGraph,
showingTable,
mode,
};
const datasourceName = exploreItemState.requestedDatasourceName;
const transaction = buildQueryTransaction(queries, queryOptions, range, scanning);
let firstResponse = true;
const newQuerySub = runRequest(datasourceInstance, transaction.request)
.pipe(
// Simple throttle for live tailing, in case of > 1000 rows per interval we spend about 200ms on processing and
// rendering. In case this is optimized this can be tweaked, but also it should be only as fast as user
// actually can see what is happening.
live ? throttleTime(500) : identity,
map((data: PanelData) => preProcessPanelData(data, queryResponse))
)
.subscribe((data: PanelData) => {
if (!data.error && firstResponse) {
// Side-effect: Saving history in localstorage
const nextHistory = updateHistory(history, datasourceId, queries);
const arrayOfStringifiedQueries = queries.map(query =>
datasourceInstance?.getQueryDisplayText
? datasourceInstance.getQueryDisplayText(query)
: getQueryDisplayText(query)
);
const nextRichHistory = addToRichHistory(
richHistory || [],
datasourceId,
datasourceName,
arrayOfStringifiedQueries,
false,
'',
''
);
dispatch(historyUpdatedAction({ exploreId, history: nextHistory }));
dispatch(richHistoryUpdatedAction({ richHistory: nextRichHistory }));
// We save queries to the URL here so that only successfully run queries change the URL.
dispatch(stateSave());
}
firstResponse = false;
dispatch(queryStreamUpdatedAction({ exploreId, response: data }));
// Keep scanning for results if this was the last scanning transaction
if (getState().explore[exploreId].scanning) {
if (data.state === LoadingState.Done && data.series.length === 0) {
const range = getShiftedTimeRange(-1, getState().explore[exploreId].range);
dispatch(updateTime({ exploreId, absoluteRange: range }));
dispatch(runQueries(exploreId));
} else {
// We can stop scanning if we have a result
dispatch(scanStopAction({ exploreId }));
}
}
});
dispatch(queryStoreSubscriptionAction({ exploreId, querySubscription: newQuerySub }));
};
}
Example #13
Source File: drawtool.service.ts From WiLearning with GNU Affero General Public License v3.0 | 4 votes |
private setupEvent() {
this.fabCanvas.on('mouse:down', (e) => {
this.logger.debug('mouse:down event');
switch (this.selectedTool) {
case DrawtoolType.text :
return this.enterDrawText(e);
case DrawtoolType.rect :
return this.enterDrawRect(e);
case DrawtoolType.line :
return this.enterDrawLine(e);
case DrawtoolType.free :
this.freeDraw = true;
break;
case DrawtoolType.select :
this.selecting = true;
break;
}
});
this.syncEvent = new Observable((obs) => {
this.fabCanvas.on('mouse:move', (e) => {
if ( e.target ) {
if (this.selectedTool !== 'select' ) {
e.target.hoverCursor = this.fabCanvas.defaultCursor;
} else {
e.target.hoverCursor = this.fabCanvas.hoverCursor;
}
}
switch (this.selectedTool) {
case DrawtoolType.line :
if ( this.lining ) {
const loc = this.fabCanvas.getPointer(e.e);
this.lining.set('x2', loc.x);
this.lining.set('y2', loc.y);
this.lining.setCoords();
this.fabCanvas.renderAll();
obs.next();
}
break;
case DrawtoolType.rect :
if ( this.recting ) {
const loc = this.fabCanvas.getPointer(e.e);
const width = loc.x - this.recting.left;
const height = loc.y - this.recting.top;
this.recting.set({width, height});
this.recting.setCoords();
this.fabCanvas.renderAll();
obs.next();
}
break;
case DrawtoolType.free :
if (this.freeDraw) {
}
break;
case DrawtoolType.select :
if (e.target && this.selecting) {
obs.next();
}
}
});
}).pipe(
throttleTime(100),
).subscribe(() => {
this.document.sendSyncDocInfo();
});
this.fabCanvas.on('mouse:up', (e) => {
switch (this.selectedTool) {
case DrawtoolType.line :
if ( this.lining ) {
this.lining = undefined;
this.fabCanvas.discardActiveObject();
this.document.sendSyncDocInfo();
}
break;
case DrawtoolType.rect :
this.recting = undefined;
this.document.sendSyncDocInfo();
break;
case DrawtoolType.free :
this.freeDraw = false;
this.document.sendSyncDocInfo();
break;
case DrawtoolType.select :
this.selecting = false;
}
});
this.fabCanvas.on('object:removed', (e) => {
this.logger.debug('fabric canvas %s is removed', e.target);
this.document.sendSyncDocInfo();
});
this.fabCanvas.on('object:modified', (e) => {
this.logger.debug('fabric canvas object modified , %s', e.target);
this.document.sendSyncDocInfo();
});
this.fabCanvas.on('path:created', (e) => {
this.logger.debug('path:created event, ', e);
(e as any).path.opacity = 0.3;
});
this.fabCanvas.on('object:added', (e) => {
this.logger.debug('object added event');
});
this.fabCanvas.on('text:changed', (e) => {
this.logger.debug('text changed event');
this.document.sendSyncDocInfo();
});
}