rxjs#OperatorFunction TypeScript Examples
The following examples show how to use
rxjs#OperatorFunction.
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: utils.ts From rubic-app with GNU General Public License v3.0 | 7 votes |
/**
* Combination of switchMap and iif.
* @param condition Condition which Observable should be chosen.
* @param trueResultFn An Observable that will be subscribed if condition is true.
* @param falseResultFn An Observable that will be subscribed if condition is false.
*/
export function switchIif<A = void, T = never, F = never>(
condition: (args: A) => boolean,
trueResultFn: (args: A) => Observable<T>,
falseResultFn: (args: A) => Observable<F>
): OperatorFunction<A, T | F> {
return switchMap((args: A) =>
iif(
() => condition(args),
defer(() => trueResultFn(args)),
defer(() => falseResultFn(args))
)
);
}
Example #2
Source File: map-and-cache-elements.ts From s-libs with MIT License | 6 votes |
export function mapAndCacheElements<UpstreamType, DownstreamType>(
buildCacheKey: (upstreamItem: UpstreamType, key: keyof any) => any,
buildDownstreamItem: BuildDownstreamItem<UpstreamType, DownstreamType>,
): OperatorFunction<UpstreamType | null | undefined, DownstreamType[]> {
let cache = new Map<any, DownstreamType>();
return map((upstreamItems: any) => {
const nextCache = new Map<any, DownstreamType>();
const downstreamItems = _map(upstreamItems, (upstreamItem, key) => {
const cacheKey = buildCacheKey(upstreamItem, key);
let downstreamItem: DownstreamType;
if (cache.has(cacheKey)) {
downstreamItem = cache.get(cacheKey)!;
} else if (nextCache.has(cacheKey)) {
downstreamItem = nextCache.get(cacheKey)!;
} else {
downstreamItem = buildDownstreamItem(upstreamItem, key);
}
nextCache.set(cacheKey, downstreamItem);
return downstreamItem;
});
cache = nextCache;
return downstreamItems;
});
}
Example #3
Source File: distinct-unique-key.operator.ts From etherspot-sdk with MIT License | 6 votes |
/**
* @ignore
*/
export function distinctUniqueKey<T, K extends keyof T>(key: K): OperatorFunction<T, T[K]> {
return (input$) =>
input$.pipe(
map((value) => {
return (value ? value : { [key]: null }) as T;
}),
distinctUntilKeyChanged(key, deepCompare),
pluck(key),
);
}
Example #4
Source File: run-zone.ts From ngx-operators with MIT License | 6 votes |
export function runOutsideZone<T>(zone: NgZone): OperatorFunction<T, T> {
return source => {
return new Observable(subscriber => {
return source.subscribe(
(value: T) => zone.runOutsideAngular(() => subscriber.next(value)),
(e: any) => zone.runOutsideAngular(() => subscriber.error(e)),
() => zone.runOutsideAngular(() => subscriber.complete())
);
});
};
}
Example #5
Source File: run-zone.ts From ngx-operators with MIT License | 6 votes |
export function runInZone<T>(zone: NgZone): OperatorFunction<T, T> {
return source => {
return new Observable(subscriber => {
return source.subscribe(
(value: T) => zone.run(() => subscriber.next(value)),
(e: any) => zone.run(() => subscriber.error(e)),
() => zone.run(() => subscriber.complete())
);
});
};
}
Example #6
Source File: subscriber.ts From pebula-node with MIT License | 6 votes |
export function SbIntercept(...interceptors: Array<SbInterceptor | Type<SbInterceptor>>) {
return <T extends Record<K, OperatorFunction<SbContext, any>>, K extends string>(target: T, key: K): void => {
const ctrlInterceptors: SbInterceptorMetadataForTarget
= Reflect.getMetadata(SERVICE_BUS_INTERCEPTORS_METADATA, target) || new Map<string | symbol, Array<SbInterceptor | Type<SbInterceptor>>>();
if (ctrlInterceptors.size === 0) {
Reflect.defineMetadata(SERVICE_BUS_INTERCEPTORS_METADATA, ctrlInterceptors, target);
}
if (!ctrlInterceptors.has(key)) {
ctrlInterceptors.set(key, []);
}
ctrlInterceptors.get(key).push(...interceptors);
};
}
Example #7
Source File: subscriber-route-handler.ts From pebula-node with MIT License | 6 votes |
async verifyAndCreate<R extends 'pipe' | 'method'>(routeInstructions: RouteToCommit<R, T>,
context: SbSubscriberRoutingContext,
configurator?: SbConfigurator): Promise<void> {
const options = routeInstructions.subscriber.metaOptions as SbSubscriberTypeMap[T];
const { handler } = routeInstructions;
if (configurator && !!options.provision) {
try {
await this.verify(options, configurator);
} catch (error) {
await context.errorHandler.onError(new SbErrorEvent('verify', options, error))
}
}
const messageHandler = routeInstructions.type === 'method'
? this.createMethodHandler(routeInstructions.subscriber, handler as MessageHandler)
: this.createPipeHandler(routeInstructions.subscriber, handler as OperatorFunction<SbContext, SbContext>, routeInstructions)
;
try {
await registerMessageHandler(
this.createReceiver(context, options),
messageHandler,
error => {
if (error instanceof WrappedError) {
context.errorHandler.onMessageError(new SbMessageErrorEvent(options, error.error));
} else {
context.errorHandler.onError(new SbErrorEvent('listening', options, error));
}
},
options.handlerOptions
);
} catch (error) {
await context.errorHandler.onError(new SbErrorEvent('register', options, error));
}
}
Example #8
Source File: subscriber-route-handler.ts From pebula-node with MIT License | 6 votes |
private createPipeHandler(metadata: SbSubscriberMetadata<T>, handler: OperatorFunction<SbContext, SbContext>, routeInstructions: RouteToCommit) {
const consumer = createConsumer(routeInstructions);
return async (message: ServiceBusMessage) => {
const context = new SbContext([metadata, message]);
const done = async () => handler(of(context)).pipe(mapTo(context)).toPromise();
await consumer.intercept(context, done).then(safeResolveResult).catch(WrappedError.wrapPromise);
};
}
Example #9
Source File: create-operator-function.spec.ts From s-libs with MIT License | 6 votes |
/**
* This is the example from the documentation. Keep it in sync.
*/
function map<I, O>(fn: (input: I) => O): OperatorFunction<I, O> {
return createOperatorFunction<I, O>((subscriber, destination) => {
subscriber.next = (value): void => {
destination.next(fn(value));
};
});
}
Example #10
Source File: create-operator-function.ts From s-libs with MIT License | 6 votes |
/**
* Use this to create a complex pipeable operator. It is usually better style to compose existing operators than to create a brand new one, but when you need full control this can reduce some boilerplate.
*
* The supplied `subscriber` will act as a simple pass-through of all values, errors, and completion to `destination`. Modify it for your needs.
*
* A simple example, recreating the "map" operator:
* ```ts
* function map<I, O>(fn: (input: I) => O) {
* return createOperatorFunction<I, O>(
* (subscriber, destination) => {
* subscriber.next = (value) => {
* destination.next(fn(value));
* };
* },
* );
* }
* ```
*
* For a more complex example, check the source of `skipAfter`.
*/
export function createOperatorFunction<
SourceType,
DestinationType = SourceType,
>(
modifySubscriber: (
subscriber: RequiredSubscriber<SourceType>,
destination: Observer<DestinationType>,
) => void,
): OperatorFunction<SourceType, DestinationType> {
return (source: Observable<SourceType>): Observable<DestinationType> =>
new Observable<DestinationType>((destination) => {
const subscriber = new Subscriber<SourceType>(destination);
modifySubscriber(subscriber, destination);
return source.subscribe(subscriber);
});
}
Example #11
Source File: catchTxError.ts From anchor-web-app with Apache License 2.0 | 6 votes |
catchTxError = <TxResult>(
params: CatchTxErrorParams,
): OperatorFunction<TxResultRendering<TxResult>, any> => {
const { txErrorReporter } = params;
return catchError((error) => {
const errorId = txErrorReporter ? txErrorReporter(error) : error.message;
if (errorContains(error, TxError.TxAlreadyProcessed)) {
return Promise.resolve<TxResultRendering>({
value: null,
phase: TxStreamPhase.SUCCEED,
receipts: [],
});
}
if (errorContains(error, TxError.TxInvalid)) {
return formatTxErrorResult(error, errorId, TxError.TxInvalid);
}
if (errorContains(error, TxError.TxHashInvalid)) {
return formatTxErrorResult(error, errorId, TxError.TxHashInvalid);
}
return Promise.resolve<TxResultRendering>({
value: null,
phase: TxStreamPhase.FAILED,
failedReason: { error: error?.data?.message ?? error?.message, errorId },
receipts: [],
});
});
}
Example #12
Source File: map-to-latest-from.ts From s-libs with MIT License | 6 votes |
/**
* Emits the latest value of the given Observable every time the source Observable emits a value.
*
* ```
* source: -1---2--3------4-|
* inner: ---a------b--c---|
* mapToLastFrom(inner): -----a--a------c-|
* ```
*/
export function mapToLatestFrom<T>(
inner$: Observable<T>,
): OperatorFunction<any, T> {
return flow(
withLatestFrom(inner$),
map(([_, inner]) => inner),
);
}
Example #13
Source File: misc-helpers.ts From s-libs with MIT License | 6 votes |
export function testUserFunctionError(
buildOperator: (thrower: () => never) => OperatorFunction<any, any>,
upstreamValue: any,
): () => void {
return marbleTest(({ hot, expectObservable, expectSubscriptions }) => {
const thrower = (): never => {
// eslint-disable-next-line @typescript-eslint/no-throw-literal -- this is the error TestScheduler expects when it sees "#"
throw 'error';
};
const source = hot('-1-', { 1: upstreamValue });
const expect1 = ' -# ';
const expect2 = ' -a-';
const allSubs = ' ^! ';
expectObservable(source.pipe(buildOperator(thrower))).toBe(expect1);
expectObservable(source.pipe(buildOperator(thrower))).toBe(expect1);
expectObservable(
source.pipe(
buildOperator(thrower),
catchError(() => new BehaviorSubject('a')),
),
).toBe(expect2);
expectSubscriptions(source.subscriptions).toBe([allSubs, allSubs, allSubs]);
});
}
Example #14
Source File: misc-helpers.ts From s-libs with MIT License | 6 votes |
export function testUnsubscribePropagation(
buildOperator: () => OperatorFunction<any, any>,
): () => void {
return marbleTest(({ hot, expectObservable, expectSubscriptions }) => {
const source = hot('-');
const sub1 = '-^---! ';
const sub2 = '---^---!';
expectObservable(source.pipe(buildOperator()), sub1).toBe('-');
expectObservable(source.pipe(buildOperator()), sub2).toBe('-');
expectSubscriptions(source.subscriptions).toBe([sub1, sub2]);
});
}
Example #15
Source File: misc-helpers.ts From s-libs with MIT License | 6 votes |
export function testErrorPropagation(
buildOperator: () => OperatorFunction<any, any>,
): () => void {
return marbleTest(({ hot, expectObservable, expectSubscriptions }) => {
const source = hot('-#');
const subs = ' ^!';
const expected = ' -#';
expectObservable(source.pipe(buildOperator())).toBe(expected);
expectObservable(source.pipe(buildOperator())).toBe(expected);
expectSubscriptions(source.subscriptions).toBe([subs, subs]);
});
}
Example #16
Source File: misc-helpers.ts From s-libs with MIT License | 6 votes |
export function testCompletionPropagation(
buildOperator: () => OperatorFunction<any, any>,
): () => void {
return marbleTest(({ hot, expectObservable, expectSubscriptions }) => {
const source = hot('----|');
const sub1 = ' ^----';
const sourceSub1 = '^---!';
const sub2 = ' --^--';
const sourceSub2 = '--^-!';
const expected = ' ----|';
expectObservable(source.pipe(buildOperator()), sub1).toBe(expected);
expectObservable(source.pipe(buildOperator()), sub2).toBe(expected);
expectSubscriptions(source.subscriptions).toBe([sourceSub1, sourceSub2]);
});
}
Example #17
Source File: index.ts From typescript-exercises with MIT License | 6 votes |
export function checkTypeScriptProject(): OperatorFunction<FileTree, ValidationError[]> {
return (parentObservable: Observable<FileTree>): Observable<ValidationError[]> => {
const service = createService();
return new Observable((subscriber) => {
let initialized = false;
let prevFiles = {} as FileContents;
const subscription = parentObservable.subscribe(async (files) => {
const contents = fileTreeToFileContents(files);
if (!initialized) {
initialized = true;
prevFiles = contents;
await service.init(contents);
} else {
const oldFiles = prevFiles;
const newFiles = contents;
prevFiles = contents; // Doing this assignment before the the update call. Just in case.
await service.updateFiles(diffFiles(oldFiles, newFiles));
}
subscriber.next(await service.getErrors());
});
subscriber.add(() => {
service.terminate();
subscription.unsubscribe();
});
});
};
}
Example #18
Source File: _catchTxError.ts From anchor-web-app with Apache License 2.0 | 6 votes |
export function _catchTxError({
helper,
txErrorReporter,
}: Params): OperatorFunction<any, any> {
return catchError((error) => {
const errorId =
txErrorReporter &&
!(error instanceof UserDenied || error instanceof Timeout)
? txErrorReporter(error)
: undefined;
return Promise.resolve<TxResultRendering>({
value: null,
phase: TxStreamPhase.FAILED,
failedReason: { error, errorId },
receipts: [helper.txHashReceipt()],
});
});
}
Example #19
Source File: utils.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
/**
* Maps stream to void: emits, and completes the stream.
*/
export function mapToVoid(): OperatorFunction<unknown, void> {
return switchMap(() => of(undefined));
}
Example #20
Source File: utils.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
/**
* Await for side-effect action like switchMap, but not modify the stream
*/
export function switchTap<T>(handler: (arg: T) => Observable<unknown>): OperatorFunction<T, T> {
return switchMap(arg => {
return handler(arg).pipe(map(() => arg));
});
}
Example #21
Source File: operators.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
/** @ignore */
export function filterByTopicChannel<T>(topic: string): OperatorFunction<MessageEvent<MessageEnvelope>, MessageEvent<MessageEnvelope<TopicMessage<T>>>> {
return pipe(
filterByChannel<TopicMessage<T>>(MessagingChannel.Topic),
filter((event: MessageEvent<MessageEnvelope<TopicMessage<T>>>): boolean => {
const messageTopic = event.data.message.topic;
return !!messageTopic && new TopicMatcher(topic).match(messageTopic).matches;
}),
);
}
Example #22
Source File: keyboard-event-dispatcher.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
private switchToKeyboardEvents(): OperatorFunction<Keystroke, KeyboardEvent> {
return switchMap(keystroke => this._keyboardEvents$
.pipe(
filter(event => event.type === keystroke.eventType),
filter(event => Keystroke.fromEvent(event).parts === keystroke.parts),
applyKeystrokeFlags(keystroke.flags),
),
);
}
Example #23
Source File: mappers.ts From gengen with MIT License | 5 votes |
export function mapGuid(): OperatorFunction<string, Guid> {
return map((z: string) => (z ? new Guid(z) : Guid.empty));
}
Example #24
Source File: mappers.ts From gengen with MIT License | 5 votes |
export function mapDate(): OperatorFunction<string, TypeOrUndefined<Date>> {
return map(toDateIn);
}
Example #25
Source File: map-and-cache-array-elements.ts From s-libs with MIT License | 5 votes |
mapAndCacheArrayElements = mapAndCacheElements as <
UpstreamType,
DownstreamType,
>(
buildCacheKey: ArrayIteratee<UpstreamType, any>,
buildDownstreamItem: ArrayIteratee<UpstreamType, DownstreamType>,
) => OperatorFunction<UpstreamType[] | null | undefined, DownstreamType[]>
Example #26
Source File: mappers.ts From gengen with MIT License | 5 votes |
export function mapIdentitySingle<TModel>(identity: { new (id: TypeOrUndefined<string>): TModel }): OperatorFunction<TypeOrUndefined<DTOIdentityType>, TypeOrUndefined<TModel>> {
return map((z: TypeOrUndefined<DTOIdentityType>) => (z ? new identity(z.id) : undefined));
}
Example #27
Source File: map-and-cache-object-elements.ts From s-libs with MIT License | 5 votes |
mapAndCacheObjectElements = mapAndCacheElements as <
UpstreamType,
DownstreamType = UpstreamType[keyof UpstreamType],
>(
buildCacheKey: ObjectIteratee<UpstreamType, any>,
buildDownstreamItem: ObjectIteratee<UpstreamType, DownstreamType>,
) => OperatorFunction<UpstreamType | null | undefined, DownstreamType[]>
Example #28
Source File: mappers.ts From gengen with MIT License | 5 votes |
export function mapIdentityCollection<TModel>(identity: { new (id: TypeOrUndefined<string>): TModel }): OperatorFunction<DTOIdentityType[], TModel[]> {
return map((z: DTOIdentityType[]) => z.map((x) => new identity(x.id)));
}
Example #29
Source File: with-history.ts From s-libs with MIT License | 5 votes |
export function withHistory<T>(count: number): OperatorFunction<T, T[]> {
return scan<T, T[]>((buf, value) => [value, ...buf.slice(0, count)], []);
}