rxjs#pipe TypeScript Examples

The following examples show how to use rxjs#pipe. 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: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
async onEditName(): Promise<void> {
    const wallet = await this.wallet$.pipe(take(1)).toPromise();

    if (!wallet) {
      // TODO: add error here later
      return;
    }
    const drawerRef = this.nzDrawerService.create<EditWalletNameComponent>({
      nzContent: EditWalletNameComponent,
      nzTitle: this.translateService.instant('SETTINGS.REGISTERED_WALLET_DETAILS.EDIT_NAME'),
      nzWrapClassName: 'drawer-full-w-320',
      nzContentParams: {
        wallet
      }
    });

    drawerRef.open();
  }
Example #2
Source File: Api.ts    From majsoul-api with MIT License 6 votes vote down vote up
constructor(private readonly apiResources: ApiResources) {
		this.protobufRoot = Root.fromJSON(this.apiResources.protobufDefinition);
		this.clientVersion = `web-${this.apiResources.version.slice(0, -2)}`;
		console.log(`Client version: [${this.clientVersion}]`);
		this.codec = new Codec(this.protobufRoot);
		const serverIndex = Math.floor(Math.random() * this.apiResources.serverList.servers.length);
		this.connection = new Connection(`wss://${this.apiResources.serverList.servers[serverIndex]}`);
		this.notifications = this.connection.messages.pipe(filter(message => message.type === MessageType.Notification), map(message => this.codec.decode(message.data)));
		this.rpc = new RpcImplementation(this.connection, this.protobufRoot);
		this.lobbyService = this.rpc.getService("Lobby");
	}
Example #3
Source File: util.ts    From ngrx-issue-tracker with MIT License 6 votes vote down vote up
withLatestFromDeferred = <A, B>(other: Observable<B>) =>
  pipe(concatMap((value: A) => of(value).pipe(withLatestFrom(other))))
Example #4
Source File: lazy.service.ts    From ng-util with MIT License 6 votes vote down vote up
/**
   * Monitor for the finished of `paths`
   *
   * - It's recommended to pass the value in accordance with the `load()` method
   */
  monitor(paths?: string | Array<string | NuLazyResources>): Observable<NuLazyResult[]> {
    const libs = this.fixPaths(paths);

    const pipes = [share(), filter((ls: NuLazyResult[]) => ls.length !== 0)];

    if (libs.length > 0) {
      pipes.push(
        filter(
          (ls: NuLazyResult[]) => ls.length === libs.length && ls.every(v => v.status === 'ok' && libs.find(lw => lw.path === v.path)),
        ),
      );
    }

    return this._notify.asObservable().pipe(pipe.apply(this, pipes as any) as any);
  }
Example #5
Source File: operators.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/** @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 #6
Source File: angular-zone-message-client-decorator.snippets.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
// end::intent-client-decorator[]

// tag::emit-inside-angular[]
function synchronizeWithAngular<T>(zone: NgZone): MonoTypeOperatorFunction<T> {
  return pipe(
    subscribeInside(continueFn => zone.runOutsideAngular(continueFn)),
    observeInside(continueFn => zone.run(continueFn)),
  );
}
Example #7
Source File: angular-zone-message-client-decorator.snippets.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public decorate(intentClient: IntentClient): IntentClient { // <2>
    const zone = this._zone;
    return new class implements IntentClient {

      public publish<T = any>(intent: Intent, body?: T, options?: IntentOptions): Promise<void> {
        return intentClient.publish(intent, body, options);
      }

      public request$<T>(intent: Intent, body?: any, options?: IntentOptions): Observable<TopicMessage<T>> {
        return intentClient.request$<T>(intent, body, options).pipe(synchronizeWithAngular(zone)); // <3>
      }

      public observe$<T>(selector?: Intent): Observable<IntentMessage<T>> {
        return intentClient.observe$<T>(selector).pipe(synchronizeWithAngular(zone)); // <3>
      }

      public onIntent<IN = any, OUT = any>(selector: IntentSelector, callback: (intentMessage: IntentMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {
        return intentClient.onIntent(selector, callback);
      }
    };
  }
Example #8
Source File: angular-zone-message-client-decorator.snippets.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public decorate(messageClient: MessageClient): MessageClient { // <2>
    const zone = this._zone;
    return new class implements MessageClient {

      public publish<T = any>(topic: string, message?: T, options?: PublishOptions): Promise<void> {
        return messageClient.publish(topic, message, options);
      }

      public request$<T>(topic: string, request?: any, options?: RequestOptions): Observable<TopicMessage<T>> {
        return messageClient.request$<T>(topic, request, options).pipe(synchronizeWithAngular(zone)); // <3>
      }

      public observe$<T>(topic: string): Observable<TopicMessage<T>> {
        return messageClient.observe$<T>(topic).pipe(synchronizeWithAngular(zone)); // <3>
      }

      public onMessage<IN = any, OUT = any>(topic: string, callback: (message: TopicMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {
        return messageClient.onMessage(topic, callback);
      }

      public subscriberCount$(topic: string): Observable<number> {
        return messageClient.subscriberCount$(topic).pipe(synchronizeWithAngular(zone)); // <3>
      }
    };
  }
Example #9
Source File: ng-zone-decorators.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public decorate(intentClient: IntentClient): IntentClient {
    const zone = this._zone;
    return new class implements IntentClient {

      public publish<T = any>(intent: Intent, body?: T, options?: IntentOptions): Promise<void> {
        return intentClient.publish(intent, body, options);
      }

      public request$<T>(intent: Intent, body?: any, options?: IntentOptions): Observable<TopicMessage<T>> {
        return intentClient.request$<T>(intent, body, options).pipe(synchronizeWithAngular(zone));
      }

      public observe$<T>(selector?: Intent): Observable<IntentMessage<T>> {
        return intentClient.observe$<T>(selector).pipe(synchronizeWithAngular(zone));
      }

      public onIntent<IN = any, OUT = any>(selector: IntentSelector, callback: (intentMessage: IntentMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {
        return intentClient.onIntent(selector, callback);
      }
    };
  }
Example #10
Source File: ng-zone-decorators.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public decorate(messageClient: MessageClient): MessageClient {
    const zone = this._zone;
    return new class implements MessageClient {

      public publish<T = any>(topic: string, message?: T, options?: PublishOptions): Promise<void> {
        return messageClient.publish(topic, message, options);
      }

      public request$<T>(topic: string, request?: any, options?: RequestOptions): Observable<TopicMessage<T>> {
        return messageClient.request$<T>(topic, request, options).pipe(synchronizeWithAngular(zone));
      }

      public observe$<T>(topic: string): Observable<TopicMessage<T>> {
        return messageClient.observe$<T>(topic).pipe(synchronizeWithAngular(zone));
      }

      public onMessage<IN = any, OUT = any>(topic: string, callback: (message: TopicMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {
        return messageClient.onMessage(topic, callback);
      }

      public subscriberCount$(topic: string): Observable<number> {
        return messageClient.subscriberCount$(topic).pipe(synchronizeWithAngular(zone));
      }
    };
  }
Example #11
Source File: ng-zone-decorators.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public decorate(delegate: IntentClient): IntentClient {
    const zone = this._zone;
    return new class implements IntentClient {

      public publish<T = any>(intent: Intent, body?: T, options?: IntentOptions): Promise<void> {
        return delegate.publish(intent, body, options);
      }

      public request$<T>(intent: Intent, body?: any, options?: IntentOptions): Observable<TopicMessage<T>> {
        return delegate.request$<T>(intent, body, options).pipe(synchronizeWithAngular(zone));
      }

      public observe$<T>(selector?: Intent): Observable<IntentMessage<T>> {
        return delegate.observe$<T>(selector).pipe(synchronizeWithAngular(zone));
      }

      public onIntent<IN = any, OUT = any>(selector: IntentSelector, callback: (intentMessage: IntentMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {
        return delegate.onIntent(selector, callback);
      }
    };
  }
Example #12
Source File: ng-zone-decorators.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public decorate(delegate: MessageClient): MessageClient {
    const zone = this._zone;
    return new class implements MessageClient {

      public publish<T = any>(topic: string, message?: T, options?: PublishOptions): Promise<void> {
        return delegate.publish(topic, message, options);
      }

      public request$<T>(topic: string, request?: any, options?: RequestOptions): Observable<TopicMessage<T>> {
        return delegate.request$<T>(topic, request, options).pipe(synchronizeWithAngular(zone));
      }

      public observe$<T>(topic: string): Observable<TopicMessage<T>> {
        return delegate.observe$<T>(topic).pipe(synchronizeWithAngular(zone));
      }

      public onMessage<IN = any, OUT = any>(topic: string, callback: (message: TopicMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {
        return delegate.onMessage(topic, callback);
      }

      public subscriberCount$(topic: string): Observable<number> {
        return delegate.subscriberCount$(topic).pipe(synchronizeWithAngular(zone));
      }
    };
  }
Example #13
Source File: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
groupedWalletAccounts$: Observable<IWalletsAccount[]> = this.walletAccounts$
    .pipe(map(accounts =>
      accounts.reduce((all: { [publicKey: string]: IWalletsAccount }, current) => {
        return !all[current.publicKey]
          ? ({ ...all, [current.publicKey]: current })
          : all;
      }, {})
    ))
    .pipe(map(obj => Object.values(obj)));
Example #14
Source File: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
async onCreateAccount(): Promise<void> {
    const wallet = await this.wallet$.pipe(take(1)).toPromise();

    if (!wallet) {
      return ;
    }

    const drawerRef = this.nzDrawerService.create<AddAccountComponent>({
      nzContent: AddAccountComponent,
      nzWrapClassName: 'drawer-full-w-320',
      nzTitle: this.translateService.instant('SETTINGS.REGISTERED_WALLET_DETAILS.ADD_ACCOUNT_TITLE'),
      nzContentParams: {
        parentWallet: wallet
      }
    });

    drawerRef.open();
  }
Example #15
Source File: ng-zone-decorators.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 5 votes vote down vote up
function synchronizeWithAngular<T>(zone: NgZone): MonoTypeOperatorFunction<T> {
  return pipe(
    subscribeInside(continueFn => zone.runOutsideAngular(continueFn)),
    observeInside(continueFn => zone.run(continueFn)),
  );
}
Example #16
Source File: ng-zone-decorators.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 5 votes vote down vote up
function synchronizeWithAngular<T>(zone: NgZone): MonoTypeOperatorFunction<T> {
  return pipe(
    subscribeInside(continueFn => zone.runOutsideAngular(continueFn)),
    observeInside(continueFn => zone.run(continueFn)),
  );
}
Example #17
Source File: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
walletAccounts$: Observable<IWalletsAccount[]> = this.wallet$
    .pipe(filter<any>(wallet => !!wallet))
    .pipe(switchMap((wallet: IWallet) =>
      this.walletsAccountsQuery.selectAll({ filterBy: entity => entity.walletId === wallet._id })
    ));
Example #18
Source File: messaging.model.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns an Observable that mirrors the source Observable unless receiving a message with
 * a response status code greater than or equal to 400. Then, the stream will end with an
 * {@link RequestError error} and the source Observable unsubscribed.
 *
 * When receiving a message with the response status code {@link ResponseStatusCodes.TERMINAL},
 * the Observable emits this message and completes.
 *
 * If a message does not include a response status code, the message is emitted as is.
 *
 * Note that this operator is installed in {@link MessageClient.request$} and {@link IntentClient.request$}.
 *
 * @category Messaging
 */
export function throwOnErrorStatus<BODY>(): MonoTypeOperatorFunction<TopicMessage<BODY>> {
  return pipe(
    mergeMap((message: TopicMessage<BODY>): Observable<TopicMessage<BODY>> => {
      const status = message.headers.get(MessageHeaders.Status) ?? ResponseStatusCodes.OK;
      if (status < 400) {
        return of(message); // 1xx: informational responses, 2xx: successful responses, 4xx: client errors, 5xx: server errors
      }

      if (typeof message.body === 'string') {
        const messageBody: string = message.body;
        return throwError(() => new RequestError(messageBody, status, message));
      }

      switch (status) {
        case ResponseStatusCodes.BAD_REQUEST: {
          return throwError(() => new RequestError('The receiver could not understand the request due to invalid syntax.', status, message));
        }
        case ResponseStatusCodes.NOT_FOUND: {
          return throwError(() => new RequestError('The receiver could not find the requested resource.', status, message));
        }
        case ResponseStatusCodes.ERROR: {
          return throwError(() => new RequestError('The receiver encountered an internal error.', status, message));
        }
        default: {
          return throwError(() => new RequestError('Request error.', status, message));
        }
      }
    }),
    takeWhile((message: TopicMessage<BODY>) => {
      return message.headers.get(MessageHeaders.Status) !== ResponseStatusCodes.TERMINAL;
    }, true),
    filter((message: TopicMessage<BODY>) => {
      const isTerminalMessage = message.headers.get(MessageHeaders.Status) === ResponseStatusCodes.TERMINAL;
      return (!isTerminalMessage || message.body !== undefined);
    }),
  );
}
Example #19
Source File: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
wallet$ = this.walletId$
    .pipe(switchMap(walletId => this.walletsQuery.selectEntity(walletId)));
Example #20
Source File: microfrontend-fixture.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 5 votes vote down vote up
/**
   * Serves the specified script, but unlike {@link loadScript}, does not load it into the iframe.
   *
   * Returns a handle to obtain the script's URL and notifier Promise that resolves when loaded the script.
   * Using the returned URL, the script can be loaded via {@link MicrofrontendFixture.setUrl} or from within a script via `location.href`.
   *
   * See {@link loadScript} for more information about the transpilation of the script.
   *
   * @param scriptPath - Specifies the location of the script (relative to the "src" folder of the project, e.g., "./lib/microfrontend.script.ts". The file name must end with ".script.ts".
   * @param functionName - Specifies the function in the specified script which to transpile to JavaScript. That function will be loaded into the iframe and invoked.
   * @param args - Specifies optional arguments to be passed to the function. Arguments are passed as first argument in the form of a dictionary.
   * @return Handle to obtain the script's URL and notifier Promise that resolves when loaded the script.
   */
  public serveScript(scriptPath: string, functionName: string, args?: Dictionary): {url: string; whenLoaded: Promise<void>} {
    if (!scriptPath.endsWith('.script.ts')) {
      throw Error(`[MicrofrontendFixtureError] Expected script file name to end with '.script.ts', but was ${scriptPath}.`);
    }

    const uuid = UUID.randomUUID();
    const channels: MessageChannels = {
      next: `onnext@${uuid}`,
      error: `onerror@${uuid}`,
      complete: `oncomplete@${uuid}`,
      load: `onload@${uuid}`,
    };
    const html = this.createHtmlToInvokeScript(scriptPath, functionName, args || {}, channels);
    const url = URL.createObjectURL(new Blob([html], {type: 'text/html'}));
    this._disposables.add(() => URL.revokeObjectURL(url));

    // Emit messages sent by the script to the fixture.
    const message$ = new ReplaySubject(Infinity);
    const next$ = fromEvent<MessageEvent>(window, 'message').pipe(filterByChannel(channels.next));
    const error$ = fromEvent<MessageEvent>(window, 'message').pipe(filterByChannel(channels.error), mergeMap(error => throwError(() => Error(error))));
    const complete$ = fromEvent<MessageEvent>(window, 'message').pipe(filterByChannel(channels.complete));
    const load$ = fromEvent<MessageEvent>(window, 'message').pipe(filterByChannel(channels.load));
    merge(next$, error$)
      .pipe(takeUntil(merge(complete$, this._unmount$)))
      .subscribe(message$);

    const whenLoaded = new Promise<void>((resolve, reject) => {
      merge(load$, error$)
        .pipe(
          take(1),
          finalize(() => this.message$ = message$),
        )
        .subscribe({
          error: reject,
          complete: resolve,
        });
    });

    return {url, whenLoaded};
  }
Example #21
Source File: microfrontend-fixture.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 5 votes vote down vote up
function filterByChannel(channel: string): OperatorFunction<MessageEvent, any> {
  return pipe(
    filter(message => message.data.channel === channel),
    map(message => message.data.value),
  );
}
Example #22
Source File: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
walletId$ = this.route.params
    .pipe(pluck('walletId'));
Example #23
Source File: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
async onRemove(): Promise<void> {
    const wallet = await this.wallet$.pipe(take(1)).toPromise();

    if (!wallet) {
      // TODO: add error message later
      return;
    }

    const walletsAccounts = await this.walletsAccountsQuery.selectAll({
      filterBy: state => state.walletId === wallet._id
    }).pipe(take(1)).toPromise();

    const drawerRef = this.nzDrawerService.create<HardConfirmComponent>({
      nzContent: HardConfirmComponent,
      nzTitle: `${this.translateService.instant('SETTINGS.REGISTERED_WALLET_DETAILS.REMOVE_WALLET_TITLE')} ${wallet.name}`,
      nzWrapClassName: 'drawer-full-w-320',
      nzContentParams: {
        title: this.translateService.instant('SETTINGS.REGISTERED_WALLET_DETAILS.REMOVE_WALLET_TITLE'),
        alertMessage: this.translateService.instant('SETTINGS.REGISTERED_WALLET_DETAILS.REMOVE_WALLET_ALERT')
      }
    });

    drawerRef.open();

    await drawerRef.afterOpen.pipe(take(1)).toPromise();

    const componentRef = drawerRef.getContentComponent();

    if (!componentRef) {
      return;
    }

    componentRef.confirmed
      .asObservable()
      .pipe(take(1))
      .pipe(tap(() => this.removingWallet$.next(true)))
      .pipe(withTransaction(() => {
        this.walletsService.removeWallets([wallet._id]);
        this.walletsAccountsService.removeAccounts(walletsAccounts.map(account => account._id));
      }))
      .pipe(takeUntil(
        merge(this.componentDestroyed$, drawerRef.afterClose)
      ))
      .subscribe(() => {
        this.router.navigate(['/settings/wallets'])
          .then();
      });
  }
Example #24
Source File: Api.ts    From majsoul-api with MIT License 5 votes vote down vote up
public subscribeToContestChatSystemMessages(id: number): Observable<any> {
		console.log("subscribeToContestChatSystemMessages", id);
		return using(
			() => ({
				unsubscribe: () => {
					this.contestSystemMessagesSubscriptions[id]--;
					if (this.contestSystemMessagesSubscriptions[id] > 0) {
						return;
					}

					delete this.contestSystemMessagesSubscriptions[id];
					this.lobbyService.rpcCall("leaveCustomizedContestChatRoom", {});
					for (const id of Object.keys(this.contestSystemMessagesSubscriptions)) {
						this.lobbyService.rpcCall<lq.IReqJoinCustomizedContestChatRoom>(
							"joinCustomizedContestChatRoom",
							{ unique_id: parseInt(id) }
						);
					}
				}
			}),
			() => {
				if (this.contestSystemMessagesSubscriptions[id] == null) {
					this.contestSystemMessagesSubscriptions[id] = 1;
					this.lobbyService.rpcCall<lq.IReqJoinCustomizedContestChatRoom>(
						"joinCustomizedContestChatRoom",
						{ unique_id: id }
					).then((resp) => {
						console.log(`tracking room '${id}'`, resp);
					});;
				} else {
					this.contestSystemMessagesSubscriptions[id]++;
				}

				return this.notifications.pipe(
					filter(
						message => message.unique_id === id
						// && message.constructor.name === "NotifyCustomContestSystemMsg"
					)
				);
			}
		);
	}