rxjs/operators#filter TypeScript Examples
The following examples show how to use
rxjs/operators#filter.
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: gas-settings.component.ts From gnosis.1inch.exchange with MIT License | 6 votes |
ngOnInit(): void {
this.gasPrice$ = this.txSpeedSelect.valueChanges.pipe(
switchMap((txSpeed: TxSpeed) => {
console.log(`txSpeed=`, txSpeed);
if (txSpeed !== 'custom') {
return of(this.getGasPrice(txSpeed));
}
return this.gasPriceInput.valueChanges.pipe(
startWith(this.gasPriceInput.value),
filter(() => !this.gasPriceInput.errors),
map((value) => {
this.customGasPrice = value;
return [formatGasPrice(value), value];
})
);
}),
map(([gasPriceBN, gasPrice]) => {
this.gasPriceChange.next({
gasPriceBN,
gasPrice,
txSpeed: this.txSpeedSelect.value
});
return gasPrice;
}),
shareReplay({ bufferSize: 1, refCount: true })
);
this.subscription.add(
this.gasPrice$.subscribe()
);
}
Example #2
Source File: GridEngine.ts From grid-engine with Apache License 2.0 | 6 votes |
/**
* @returns Observable that, whenever a specified position is entered on optionally provided layers,
* will notify with the target characters position change
*/
steppedOn(
charIds: string[],
tiles: Position[],
layer?: string[]
): Observable<
{
charId: string;
} & PositionChange
> {
return this.positionChangeFinished().pipe(
filter(
(t) =>
charIds.includes(t.charId) &&
tiles.some(
(target) => target.x === t.enterTile.x && target.y === t.enterTile.y
) &&
(layer === undefined || layer.includes(t.enterLayer))
)
);
}
Example #3
Source File: component.tsx From codedoc with MIT License | 6 votes |
export function HintBox(
this: ThemedComponentThis<CodedocTheme>,
_: any,
renderer: any
) {
const classes = this.theme.classes(HintBoxStyle);
const target$ = this.expose.in('target', new Subject<HTMLElement | undefined>());
const active$ = target$.pipe(map(el => !!el));
const top$ = combineLatest(
target$
.pipe(
map(el => el ? el.getBoundingClientRect().top : undefined)
),
fromEvent(document, 'mousemove')
.pipe(
map(e => (e as MouseEvent).clientY)
)
).pipe(
map(([top, mouseY]) => (top || mouseY) + 24)
);
const left$ = fromEvent(document, 'mousemove').pipe(map(e => (e as MouseEvent).clientX + 24));
return <div
class={rl`${classes.hintbox} ${toggleList({'active': active$.pipe(startWith(false))})}`}
style={rl`top: ${top$}px;left: ${left$}px`}
>
<span class="icon-font outline">wb_incandescent</span>
{target$.pipe(filter(el => !!el), map(el => el?.getAttribute('data-hint')))}
</div>;
}
Example #4
Source File: epics.ts From anthem with Apache License 2.0 | 6 votes |
setActiveChartTabEpic: EpicSignature = (action$, state$, deps) => {
return action$.pipe(
filter(isActionOf(Actions.onRouteChange)),
pluck("payload"),
pluck("pathname"),
filter(pathname => onChartTab(pathname)),
map(pathname => {
const { network } = state$.value.ledger.ledger;
const { activeChartTab } = state$.value.app.app;
const tab = pathname.split("/")[2];
const validTab = isChartTabValidForNetwork(tab, network);
if (validTab && validTab !== activeChartTab) {
return Actions.setActiveChartTab(validTab);
} else {
return Actions.empty("No need to update the active chart tab...");
}
}),
);
}
Example #5
Source File: artichoke.ts From closer-sdk.js with MIT License | 6 votes |
constructor(
private artichokeApi: ArtichokeApi,
private callFactory: CallFactory,
private roomFactory: RoomFactory,
private loggerService: LoggerService,
private heartbeatTimeoutMultiplier: number,
private fallbackReconnectDelayMs: number,
) {
// Do not move this as a property accessor, it must be only one object to make rx `share` operator work.
this.connection = merge(
this.artichokeApi.connection$.pipe(
filter(serverEvents.OutputHeartbeat.is),
tap((ev: serverEvents.OutputHeartbeat) => this.handleHeartbeatEvent(ev)),
ignoreElements(),
),
this.artichokeApi.connection$.pipe(
filter(serverEvents.Hello.is),
tap(ev => this.handleHelloEvent(ev)),
),
).pipe(
finalize(() => this.handleDisconnect()),
// On WebSocket error
retryWhen(errors => this.delayReconnect(errors)),
takeUntil(this.serverUnreachableEvent),
// On WebSocket gracefull close
repeatWhen(attempts => this.delayReconnect(attempts)),
// IMPORTANT
// Share the observable, so the internal logic would behave like one consistent stream
// Without this operator, if client subscribes two times, we would have
// two heartbeats answers and reconnections logic
share(),
);
}
Example #6
Source File: app.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
accountWithHorizonQuery$ = selectPersistStateInit()
.pipe(switchMap(() => {
const selectedAccount$ = this.walletsAccountsQuery.getSelectedAccount$
.pipe(filter(account => !!account))
.pipe(distinctUntilKeyChanged('_id'));
const selectedHorizonApi$ = this.horizonApisQuery.getSelectedHorizonApi$
.pipe(filter(horizon => !!horizon))
.pipe(distinctUntilKeyChanged('_id'));
return combineLatest([
selectedAccount$,
selectedHorizonApi$
]);
}));
Example #7
Source File: app.module.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
/**
* Defines scroll strategy, when page url is changed.
* Doesn't scroll if only query parameters are changed.
*/
private setScrollStrategy(): void {
this.router.events
.pipe(
filter((e: Event): e is Scroll => e instanceof Scroll),
pairwise()
)
.subscribe(([prevEvent, event]) => {
if (event.position) {
// backward navigation
this.viewportScroller.scrollToPosition(event.position);
} else if (event.anchor) {
// anchor navigation
this.viewportScroller.scrollToAnchor(event.anchor);
} else if (
prevEvent.routerEvent.urlAfterRedirects.split('?')[0] !==
event.routerEvent.urlAfterRedirects.split('?')[0]
) {
// forward navigation
this.viewportScroller.scrollToPosition([0, 0]);
}
});
}
Example #8
Source File: product.service.ts From Angular-ActionStreams with MIT License | 6 votes |
product$ = this.productSelectedAction$
.pipe(
filter(id => !!id),
switchMap(selectedProductId =>
this.http.get<Product>(`${this.productsUrl}/${selectedProductId}`)
.pipe(
tap(response => console.log(JSON.stringify(response))),
map(p => ({ ...p, profit: p.price - p.cost }) as Product),
catchError(this.handleError)
)
));
Example #9
Source File: product.service.ts From Angular-HigherOrderMapping with MIT License | 6 votes |
// Try mergeMap, switchMap, concatMap
product$ = this.productSelectedAction$
.pipe(
filter(id => !!id),
switchMap(selectedProductId =>
this.http.get<Product>(`${this.productsUrl}/${selectedProductId}`)
.pipe(
tap(response => console.log(JSON.stringify(response))),
map(p => ({ ...p, profit: p.price - p.cost }) as Product),
catchError(this.handleError)
)
));
Example #10
Source File: fileMode.component.ts From RcloneNg with MIT License | 6 votes |
ngOnInit() {
const outer = this;
this.list$ = new (class extends OperationsListFlow {
public prerequest$ = combineLatest([
outer.listTrigger,
outer.nav$.getOutput(),
outer.connectService.listCmd$.verify(this.cmd),
]).pipe(
map(
([, navNode, cmdNode]): CombErr<OperationsListFlowInNode> => {
if (navNode[1].length !== 0 || cmdNode[1].length !== 0)
return [{}, [].concat(navNode[1], cmdNode[1])] as CombErr<any>;
return [{ ...navNode[0], ...cmdNode[0] }, []];
}
),
filter(x => x[1].length !== 0 || !!x[0].remote)
);
})();
this.list$.deploy();
this.listExtends$ = new (class extends OperationsListExtendsFlow {
public prerequest$ = combineLatest([
outer.list$.getSupersetOutput(),
outer.clipboard.clipboard$.getOutput(),
]).pipe(
map(
([listNode, cbNode]): CombErr<OperationsListExtendsFlowInNode> => [
{ ...listNode[0], ...cbNode[0] },
[].concat(listNode[1], cbNode[1]),
]
)
);
})();
this.listExtends$.deploy();
this.listTrigger.next(1);
}
Example #11
Source File: app.component.ts From ng-conf-2020-workshop with MIT License | 6 votes |
public ngOnInit(): void {
this.router.events.pipe(
filter((x) => x instanceof NavigationStart)
)
.subscribe((event: NavigationStart) => {
if (event.url !== '/' && !this.navdrawer.pin) {
// Close drawer when selecting a view on mobile (unpinned)
this.navdrawer.close();
}
});
}
Example #12
Source File: epic.ts From Shopping-Cart with MIT License | 6 votes |
fetchProductListEpic: Epic = (
action$: ActionsObservable<Actions>,
_,
{ productService }: Service,
) =>
action$.pipe(
filter(isActionOf(fetchProductListAsync.request)),
switchMap(({ payload }) => {
const { items, totalProducts } = productService.getItems(
payload.currentPage,
);
return of(fetchProductListAsync.success({ items, totalProducts }));
}),
catchError(err => {
return of(fetchProductListAsync.failure(err));
}),
)
Example #13
Source File: carousel.component.ts From canopy with Apache License 2.0 | 6 votes |
setAutoPlayInterval(): void {
this.pausableTimer$ = defer(() => {
return interval(this.autoPlayDelay).pipe(
takeUntil(this.unsubscribe),
withLatestFrom(this.pause),
filter(([ , paused ]) => !paused),
map(() => this.nextCarouselItem()),
);
});
this.pausableTimer$.subscribe();
this.cd.detectChanges();
}
Example #14
Source File: language.service.ts From mylog14 with GNU General Public License v3.0 | 6 votes |
// Only update if userData.language differs from the language to be set
private setUserDataLanguageIfDifferent(language: string): Observable<any> {
return this.dataStore.userData$
.pipe(
take(1),
filter(userData => userData.language !== language),
switchMap(() => this.dataStore.updateUserData({ language })),
);
}
Example #15
Source File: bill-of-materials.component.ts From barista with Apache License 2.0 | 6 votes |
ngAfterViewInit(): void {
if (!this.searchInput) {
return;
}
fromEvent(this.searchInput.nativeElement, 'input')
.pipe(
map((event: any) => event.target.value),
filter(res => res.length > 2 || res.length === 0),
debounceTime(500),
distinctUntilChanged(),
untilDestroyed(this),
)
.subscribe((text: string) => {
this.bomGlobalFilterMessageService.send(text);
});
}