rxjs/operators#share TypeScript Examples

The following examples show how to use rxjs/operators#share. 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: rest-api-connector.service.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
//   ___ ___ ___ ___ ___ ___ _  _  ___ ___ ___ 
    //  | _ \ __| __| __| _ \ __| \| |/ __| __/ __|
    //  |   / _|| _|| _||   / _|| .` | (__| _|\__ \
    //  |_|_\___|_| |___|_|_\___|_|\_|\___|___|___/

    /**
     * get all external references
     * @param {number} [limit] the number of references to retrieve
     * @param {number} [offset] the number of references to skip
     * @param {string} [search] Only return references where the provided search text occurs in the description or url. The search is case-insensitive.
     * @returns {Observable<Paginated>} paginated data for external references
     */
    public getAllReferences(limit?: number, offset?: number, search?: string): Observable<Paginated<ExternalReference>> {
        let url = `${this.baseUrl}/references`;
        // parse params into query string
        let query = new HttpParams();
        // pagination
        if (limit) query = query.set("limit", limit.toString());
        if (offset) query = query.set("offset", offset.toString());
        if (search) query = query.set("search", encodeURIComponent(search));
        /*if (limit || offset) */ query = query.set("includePagination", "true");
        return this.http.get<Paginated<ExternalReference>>(url, {headers: this.headers, params: query}).pipe(
            tap(results => logger.log("retrieved references", results)),
            catchError(this.handleError_continue<Paginated<ExternalReference>>({data: [], pagination: {total: 0, limit: 0, offset: 0}})), // on error, trigger the error notification and continue operation without crashing (returns empty item)
            share() // multicast so that multiple subscribers don't trigger the call twice. THIS MUST BE THE LAST LINE OF THE PIPE
        )
    }
Example #2
Source File: observables.ts    From webapp with MIT License 6 votes vote down vote up
liquiditySettings$ = combineLatest([
  liquidityProtection$,
  settingsContractAddress$
]).pipe(
  switchMapIgnoreThrow(([protectionContractAddress, settingsContractAddress]) =>
    fetchLiquidityProtectionSettings({
      settingsContractAddress
    }).catch(e =>
      vxm.ethBancor.fetchLiquidityProtectionSettings({
        protectionContractAddress,
        settingsContractAddress
      })
    )
  ),
  share()
)
Example #3
Source File: auth.interceptor.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
/**
   * 续签访问令牌
   * @param token 续签令牌
   */
  private refreshToken(token: string) {
    this.refresher = this.authService.refresh(token).pipe(
      share(),
      tap(({ code, data }: Result<string>) => {
        if (code !== ResultCode.Success) {
          return this.app.logout();
        }

        this.tokenService.store(data);
      }),
      catchError((error: HttpErrorResponse) => {
        this.app.logout();
        return throwError(() => error);
      }),
      finalize(() => this.refresher = null)
    );
  }
Example #4
Source File: resize-observer.service.ts    From resize-observer with MIT License 6 votes vote down vote up
constructor(
        @Inject(ElementRef) {nativeElement}: ElementRef<Element>,
        @Inject(NgZone) ngZone: NgZone,
        @Inject(RESIZE_OBSERVER_SUPPORT) support: boolean,
        @Inject(RESIZE_OPTION_BOX) box: ResizeObserverOptions['box'],
    ) {
        let observer: ResizeObserver;

        super(subscriber => {
            if (!support) {
                subscriber.error('ResizeObserver is not supported in your browser');

                return;
            }

            observer = new ResizeObserver(entries => {
                ngZone.run(() => {
                    subscriber.next(entries);
                });
            });
            observer.observe(nativeElement, {box});

            return () => {
                observer.disconnect();
            };
        });

        return this.pipe(share());
    }
Example #5
Source File: page-visibility.ts    From common with MIT License 6 votes vote down vote up
PAGE_VISIBILITY = new InjectionToken<Observable<boolean>>(
    'Shared Observable based on `document visibility changed`',
    {
        factory: () => {
            const documentRef = inject(DOCUMENT);

            return fromEvent(documentRef, 'visibilitychange').pipe(
                startWith(0),
                map(() => documentRef.visibilityState !== 'hidden'),
                distinctUntilChanged(),
                share(),
            );
        },
    },
)
Example #6
Source File: rest-api-connector.service.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
/**
     * Factory to create a new STIX object creator (POST) function
     * @template T the type to create
     * @param {AttackType} attackType tehe type to create
     * @returns creator (POST) function
     */
    private postStixObjectFactory<T extends StixObject>(attackType: AttackType) {
        let attackClass = attackTypeToClass[attackType];
        let plural = attackTypeToPlural[attackType];
        return function<P extends T>(object: P): Observable<P> {
            let url = `${this.baseUrl}/${plural}`;
            return this.http.post(url, object.serialize(), {headers: this.headers}).pipe(
                tap(this.handleSuccess(`${this.getObjectName(object)} saved`)),
                map(result => {
                    let x = result as any;
                    if (x.stix.type == "malware" || x.stix.type == "tool") return new Software(x.stix.type, x);
                    else return new attackClass(x);
                }),
                catchError(this.handleError_raise()),
                share() // multicast so that multiple subscribers don't trigger the call twice. THIS MUST BE THE LAST LINE OF THE PIPE
            )
        }
    }
Example #7
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 #8
Source File: rest-api-connector.service.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
/**
     * Get all objects related to a data source
     * @param id the STIX ID of the data source
     * @returns list of data components related to the data source along with the data components' relationships with techniques
     */
    public getAllRelatedToDataSource(id: string): Observable<StixObject[]> {
        let dataComponents$ = this.getAllDataComponents();
        return dataComponents$.pipe(
            map(result => { // get related data component objects
                let dataComponents = result.data as DataComponent[];
                return dataComponents.filter(d => d.data_source_ref == id);
            }),
            mergeMap(dataComponents => { // get relationships for each data component
                let relatedTo = dataComponents.map(dc => this.getRelatedTo({sourceOrTargetRef: dc.stixID}));
                if (!relatedTo.length) return of(dataComponents);
                return forkJoin(relatedTo).pipe(
                    map(relationships => {
                        let all_results: StixObject[] = [];
                        for(let relationship_result of relationships) {
                            all_results = all_results.concat(relationship_result.data)
                        }
                        return all_results.concat(dataComponents);
                    })
                );
            }),
            catchError(this.handleError_continue([])),
            share()
        );
    }
Example #9
Source File: mockApiRx.ts    From guardian with Apache License 2.0 6 votes vote down vote up
MockApiRx = of({
  ...acalaRpc,
  consts: {
    prices: { stableCurrencyFixedPrice: 1e18 },
    currencies: { getNativeCurrencyId: ACA },
    cdpEngine: {
      getStableCurrencyId: AUSD,
      collateralCurrencyIds: COLLATERAL_CURRENCY_IDS
    }
  },
  query: {
    auctionManager: {
      collateralAuctions: {
        entries: () => of([[collateralAuctionsKey(0), COLLATERAL_AUCTION]])
      }
    },
    auction: {
      auctionsIndex: () => of(registry.createType('AuctionId', 1)),
      auctions: () => of(AUCTION)
    },
    dex: {
      liquidityPool: () => of(LP)
    },
    loans: {
      positions: () => of(POSITION)
    },
    cdpEngine: {
      debitExchangeRate: () => of(EXCHANGE_RATE)
    },
    acalaOracle: {
      values: () => {
        return merge([of(PRICE), timer(1000).pipe(mapTo(PRICE_UPDATED))]).pipe(concatAll(), share());
      }
    }
  },
  createType: (type: string, value: any) => registry.createType(type, value)
})
Example #10
Source File: rest-api-connector.service.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
/**
     * Get a single reference by source name
     * @param {string} source_name the reference's source_name identifier
     * @returns {Observable<ExternalReference>} the external reference with the given source_name
     */
    public getReference(source_name: string): Observable<ExternalReference> {
        let url = `${this.baseUrl}/references`;
        // parse params into query string
        let query = new HttpParams();
        query = query.set("sourceName", source_name);
        return this.http.get<ExternalReference>(url, {headers: this.headers, params: query}).pipe(
            tap(results => logger.log("retrieved reference", results)),
            catchError(this.handleError_continue<ExternalReference>()), // on error, trigger the error notification and continue operation without crashing (returns empty item)
            share() // multicast so that multiple subscribers don't trigger the call twice. THIS MUST BE THE LAST LINE OF THE PIPE
        )
    }
Example #11
Source File: records-metrics.component.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
ngOnInit(): void {
    this.results$ = this.searchService
      .search(
        'bucket',
        JSON.stringify({
          size: 0,
          track_total_hits: true,
          query: { query_string: { query: this.queryString } },
          aggs: {
            results: {
              terms: {
                field: this.field,
                size: this.count,
              },
            },
          },
        })
      )
      .pipe(
        map<unknown, RecordMetric[]>(
          (response: EsSearchResponse) =>
            response.aggregations.results.buckets.map((category) => ({
              value: category.key,
              recordCount: category.doc_count,
            })) as RecordMetric[]
        ),
        share()
      )
  }
Example #12
Source File: promotion.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public readonly tableData$ = combineLatest([
    this._tableData$.pipe(filter(notNull)),
    this._sortParameter$
  ]).pipe(
    map(([tableData, sortParameter]) =>
      tableData.slice().sort(comparators[sortParameter.sortColumn](sortParameter.descending))
    ),
    share()
  );
Example #13
Source File: artichoke.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
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 #14
Source File: key-list.component.ts    From distributed-compliance-ledger with Apache License 2.0 6 votes vote down vote up
ngOnInit() {
    const source = this.keyService.getKeyInfos().pipe(
      share()
    );

    this.total$ = source.pipe(
      pluck('total')
    );

    this.items$ = source.pipe(
      pluck('items')
    );
  }
Example #15
Source File: authentication.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Initiate authentication using the ng2-ui-auth library. The authentication process will be performed
     * in a browser popup window
     *
     * @param provider The name of the provider to use. This is the name configured in the Sinequa administration
     * console
     */
    authenticateWithProvider(provider: string): Observable<any> {
        // AuthService.authenticate opens a popup. On some platforms (Firefox) this is asynchronous
        // so we add a delay (timer(0)) so the caller can create a promise from the returned observable
        // without yielding
        const observable = timer(0).pipe(flatMap((value) => {
            const observable1 = this.authService.authenticate(provider, true).pipe(share());
            Utils.subscribe(observable1,
                (response) => {
                    // NB response should be the return value from JOAuth/JSaml json methods
                    // It can be undefined eg if the popup fails to open
                    if (response) {
                        this.processedCredentials = {
                            kind: LEGACY_PROCESSED_CREDENTIALS_KIND,
                            data: {
                                csrfToken: response.csrfToken,
                                provider
                            }
                        };
                    }
                });
            return observable1;
        }));
        return observable;
    }
Example #16
Source File: backend_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
private getFromFetchStream = (options: BackendSrvRequest) => {
    const url = parseUrlFromOptions(options);
    const init = parseInitFromOptions(options);
    return this.dependencies.fromFetch(url, init).pipe(
      mergeMap(async response => {
        const { status, statusText, ok, headers, url, type, redirected } = response;
        const textData = await response.text(); // this could be just a string, prometheus requests for instance
        let data;
        try {
          data = JSON.parse(textData); // majority of the requests this will be something that can be parsed
        } catch {
          data = textData;
        }
        const fetchResponse: FetchResponse = {
          status,
          statusText,
          ok,
          data,
          headers,
          url,
          type,
          redirected,
          config: options,
        };
        return fetchResponse;
      }),
      share() // sharing this so we can split into success and failure and then merge back
    );
  };
Example #17
Source File: artichoke-api.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
constructor(
    public sessionId: proto.ID,
    private websocketClient: WebsocketClient,
    private httpClient: HttpClient,
  ) {
    this.connectionEvent = this.websocketClient.connection$.pipe(
      tap(event => this.handleDomainEvent(event)),
      share()
    );
  }
Example #18
Source File: socket-io.adapter.ts    From nativescript-plugins with Apache License 2.0 6 votes vote down vote up
public bindMessageHandlers(
    client: any,
    handlers: MessageMappingProperties[],
    transform: (data: any) => Observable<any>,
  ) {
    const disconnect$ = fromEvent(client, DISCONNECT_EVENT).pipe(
      share(),
      first(),
    );

    handlers.forEach(({ message, callback }) => {
      const source$ = fromEvent(client, message).pipe(
        mergeMap((payload: any) => {
          const { data, ack } = this.mapPayload(payload);
          return transform(callback(data, ack)).pipe(
            filter((response: any) => !isNil(response)),
            map((response: any) => [response, ack]),
          );
        }),
        takeUntil(disconnect$),
      );
      source$.subscribe(([response, ack]) => {
        if (response.event) {
          return client.emit(response.event, response.data);
        }
        isFunction(ack) && ack(response);
      });
    });
  }
Example #19
Source File: account-list.component.ts    From distributed-compliance-ledger with Apache License 2.0 6 votes vote down vote up
ngOnInit() {
    const source = this.accountService.getAccountHeaders().pipe(
      share()
    );

    this.total$ = source.pipe(
      pluck('total')
    );

    this.items$ = source.pipe(
      pluck('items')
    );
  }
Example #20
Source File: message-broker.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
constructor() {
    this._applicationRegistry = Beans.get(ApplicationRegistry);
    this._manifestRegistry = Beans.get(ManifestRegistry);
    this._heartbeatInterval = Beans.get(CLIENT_HEARTBEAT_INTERVAL);

    // Construct a stream of messages sent by clients.
    this._clientMessage$ = fromEvent<MessageEvent>(window, 'message')
      .pipe(
        filterByTransport(MessagingTransport.ClientToBroker),
        filterByChannel(MessagingChannel.Intent, MessagingChannel.Topic, MessagingChannel.TopicSubscribe, MessagingChannel.TopicUnsubscribe),
        bufferUntil(Beans.whenRunlevel(Runlevel.Two)),
        checkOriginTrusted(),
        catchErrorAndRetry(),
        share(),
      );

    // Install client connect listeners.
    this.installClientConnectListener();
    this.installClientDisconnectListener();

    // Install message dispatchers.
    this.installTopicMessageDispatcher();
    this.installIntentMessageDispatcher();

    // Install topic subscriptions listeners.
    this.installTopicSubscribeListener();
    this.installTopicUnsubscribeListener();
    this.installTopicSubscriberCountObserver();

    // Assemble message interceptors to a chain of handlers which are called one after another. The publisher is added as terminal handler.
    this._messagePublisher = this.createMessagePublisher();
    this._intentPublisher = this.createIntentPublisher();
  }
Example #21
Source File: withdraw.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public readonly canReceive$ = this.amount.valueChanges.pipe(
    switchMap(amount => {
      if (amount === '') {
        this._rewardUsdPrice$.next(new BigNumber(0));
        return of('');
      }
      const amountInWei = new BigNumber(Web3Pure.toWei(amount.split(',').join('')));
      return of(amountInWei).pipe(
        switchMap(value => this.stakingService.calculateLeaveReward(value)),
        tap(reward =>
          this._rewardUsdPrice$.next(this.stakingService.calculateBRBCUsdPrice(reward))
        ),
        map(reward => reward.toNumber())
      );
    }),
    share(),
    takeUntil(this.destroy$)
  );
Example #22
Source File: proposed-certificates-list.component.ts    From distributed-compliance-ledger with Apache License 2.0 5 votes vote down vote up
getCertificates(): void {
    const source = this.pkiService.getAllProposedX509RootCerts().pipe(share());

    this.total$ = source.pipe(pluck('total'));
    this.items$ = source.pipe(pluck('items'));
  }
Example #23
Source File: search.tsx    From codedoc with MIT License 5 votes vote down vote up
export function GithubSearch(this: ComponentThis, options: SearchOptions, renderer: RendererLike<any, any>) {
  const query = new Subject<string>();
  const pick = new RegExp(options.pick);
  const drop = new RegExp(options.drop);
  const cache: {[q: string]: string[]} = {};

  const results = query.pipe(
    switchMap(q =>
      (q in cache) ? of({ result: cache[q] }) :     // --> respond from cache if query in cache
      ajax.getJSON<HotGithubResponse>(
        `https://api.github.com/search/code?q=${encodeURIComponent(q)}`
        + `+in:file`                                // --> search in files
        + `+path:${options.root}`                   // --> search in root directory
        + `+extension:md`                           // --> search in `.md` files
        + `+repo:${options.user}/${options.repo}`   // --> search in given repo of given user
      ).pipe(catchError(() => of(undefined)))       // --> no sweat in case of error
    ),
    map(res => 
      res ?
      ( isCached(res) ? res.result :                // --> if cached result, no need to process
        res.items
          .map(item => item.path)
          .filter(x => pick.test(x))                // --> check if it should be picked
          .filter(x => !drop.test(x))               // --> check if it shouldn't be dropped
          .map(x => x.substr(0, x.length - 3))      // --> remove the extension `.md`
          .map(x => x.substr(options.root.length))  // --> remove the root path part
          .map(x => x === '/index' ? '/' : x)       // --> turn `/index` to `/`
      ): []
    ),
    share(),
  );

  zip(query, results).pipe(                         // --> for pairs of query and result...
    tap(([query, results]) => {
      if (results.length > 0)                       // --> ...if the result is valid...
        cache[query] = results;                     // --> ...cache it.
    })
  ).subscribe();

  return <ToCSearchBtn label={options.label} query={query} results={results}/>;
}
Example #24
Source File: nav-bar.component.ts    From ng-ant-admin with MIT License 5 votes vote down vote up
constructor(private router: Router,
              private destroy$: DestroyService,
              private userInfoService: UserInfoService,
              private menuServices: MenuStoreService,
              private splitNavStoreService: SplitNavStoreService,
              private activatedRoute: ActivatedRoute, private tabService: TabService,
              private cdr: ChangeDetectorRef, private themesService: ThemeService,
              private titleServe: Title, @Inject(DOCUMENT) private doc: Document) {
    this.initMenus();

    this.subTheme$ = this.isOverMode$.pipe(switchMap(res => {
      this.isOverMode = res;
      return this.themesOptions$;
    }), tap(options => {
      this.themesMode = options.mode;
      this.isMixiMode = this.themesMode === 'mixi';
    }), share(), takeUntil(this.destroy$));

    // 监听混合模式下左侧菜单数据源
    this.subMixiModeSideMenu();
    // 监听折叠菜单事件
    this.subIsCollapsed();
    this.subAuth();
    this.router.events
      .pipe(
        filter(event => event instanceof NavigationEnd),
        tap(() => {
          this.subTheme$.subscribe(() => {
            // 主题切换为混合模式下,设置左侧菜单数据源
            // 如果放在ngInit监听里面,会在混合模式下,刷新完页面切换路由,runOutSideAngular
            if (this.isMixiMode) {
              this.setMixModeLeftMenu();
            }
          })
          // @ts-ignore
          this.routerPath = this.activatedRoute.snapshot['_routerState'].url;
          this.clickMenuItem(this.menus);
          this.clickMenuItem(this.copyMenus);
          // 是折叠的菜单并且不是over菜单,解决折叠左侧菜单时,切换tab会有悬浮框菜单的bug
          if (this.isCollapsed && !this.isOverMode) {
            this.closeMenuOpen(this.menus);
          }

          // 顶部菜单模式,并且不是over模式,解决顶部模式时,切换tab会有悬浮框菜单的bug
          if (this.themesMode === 'top' && !this.isOverMode) {
            this.closeMenu();
          }
        }),
        map(() => this.activatedRoute),
        map((route) => {
          while (route.firstChild) {
            route = route.firstChild;
          }
          return route;
        }),
        filter((route) => {
          return route.outlet === 'primary';
        }),
        mergeMap((route) => {
          return route.data;
        }),
        takeUntil(this.destroy$),
      )
      .subscribe((routeData) => {
        // 详情页是否是打开新tab页签形式
        let isNewTabDetailPage = routeData['newTab'] === 'true';
        this.tabService.addTab({
          title: routeData['title'],
          path: this.routerPath,
          relatedLink: routeData['relatedLink'] ? routeData['relatedLink'] : [],
        }, isNewTabDetailPage);
        this.tabService.findIndex(this.routerPath);
        this.titleServe.setTitle(routeData['title'] + ' - Ant Design');
        // 混合模式时,切换tab,让左侧菜单也相应变化
        this.setMixModeLeftMenu();
      });
  }
Example #25
Source File: initiate-search.ts    From js-client with MIT License 5 votes vote down vote up
QUERY_INIT_RESULTS: Observable<{
	requestID: string;
	msg: RawSearchInitiatedMessageReceived;
}> = QUERY_QUEUE.pipe(
	// When a "request" is received, create an Observable to listen to incoming RawSearchInitiatedMessageReceived,
	// and send a RawInitiateSearchMessageSent when ready. concatMap ensures we only have one sender/listener at a time.
	// We won't send the next request until we've heard a response for the current request.
	concatMap(({ requestID, rawSubscription, query, options }) =>
		// Listen for incoming messages on the search websocket
		rawSubscription.received$.pipe(
			withLatestFrom(
				// Wait to send RawInitiateSearchMessageSent until concatMap has subscribed to the outer Observable
				defer(() => {
					return rawSubscription.send(<RawInitiateSearchMessageSent>{
						type: 'search',
						data: {
							Addendum: options.initialFilterID ? { filterID: options.initialFilterID } : {},
							Background: false,
							Metadata: options.metadata ?? {},
							SearchStart: options.range === 'preview' ? null : options.range?.[0]?.toISOString() ?? null,
							SearchEnd: options.range === 'preview' ? null : options.range?.[1]?.toISOString() ?? null,
							SearchString: query,
							Preview: options.range === 'preview',
							NoHistory: options.noHistory ?? false,
						},
					});
				}),
			),
			// Discard the (void) result from rawSubscription.send(). We only need the messages coming from received$
			map(([msg]) => msg),

			// Filter to only RawSearchInitiatedMessageReceived messages
			filter((msg): msg is RawSearchInitiatedMessageReceived => {
				try {
					const _msg = <RawSearchInitiatedMessageReceived>msg;

					// the type is about all we can count on -- in Error cases, Metadata and Addendum are unavailable.
					return _msg.type === 'search';
				} catch {
					return false;
				}
			}),

			// There's only one Received per Sent, so we're done after the first
			first(),

			// Include the internal "request" ID
			map(msg => ({ requestID, msg })),
		),
	),
	share(),
)
Example #26
Source File: TraderInfoTask.ts    From guardian with Apache License 2.0 5 votes vote down vote up
getTraderState = (apiRx: ApiRx, account: AccountId, poolId: LiquidityPoolId, period: number) => {
  const liquidityPoolId = apiRx.createType('LiquidityPoolId', poolId);
  return timer(0, period).pipe(
    switchMap(() => apiRx.rpc.margin.traderState(account, liquidityPoolId)),
    distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
    share()
  );
}
Example #27
Source File: approved-certificates-list.component.ts    From distributed-compliance-ledger with Apache License 2.0 5 votes vote down vote up
getCertificates(): void {
    const source = this.pkiService.getAllX509Certs().pipe(share());

    this.total$ = source.pipe(pluck('total'));
    this.items$ = source.pipe(pluck('items'));
  }
Example #28
Source File: runRequest.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
/**
 * This function handles the excecution of requests & and processes the single or multiple response packets into
 * a combined PanelData response.
 * It will
 *  * Merge multiple responses into a single DataFrame array based on the packet key
 *  * Will emit a loading state if no response after 50ms
 *  * Cancel any still running network requests on unsubscribe (using request.requestId)
 */
export function runRequest(datasource: DataSourceApi, request: DataQueryRequest): Observable<PanelData> {
  let state: RunningQueryState = {
    panelData: {
      state: LoadingState.Loading,
      series: [],
      request: request,
      timeRange: request.range,
    },
    packets: {},
  };

  // Return early if there are no queries to run
  if (!request.targets.length) {
    request.endTime = Date.now();
    state.panelData.state = LoadingState.Done;
    return of(state.panelData);
  }

  const dataObservable = callQueryMethod(datasource, request).pipe(
    // Transform response packets into PanelData with merged results
    map((packet: DataQueryResponse) => {
      if (!isArray(packet.data)) {
        throw new Error(`Expected response data to be array, got ${typeof packet.data}.`);
      }

      request.endTime = Date.now();

      state = processResponsePacket(packet, state);

      return state.panelData;
    }),
    // handle errors
    catchError(err =>
      of({
        ...state.panelData,
        state: LoadingState.Error,
        error: processQueryError(err),
      })
    ),
    tap(getAnalyticsProcessor(datasource)),
    // finalize is triggered when subscriber unsubscribes
    // This makes sure any still running network requests are cancelled
    finalize(cancelNetworkRequestsOnUnsubscribe(request)),
    // this makes it possible to share this observable in takeUntil
    share()
  );

  // If 50ms without a response emit a loading state
  // mapTo will translate the timer event into state.panelData (which has state set to loading)
  // takeUntil will cancel the timer emit when first response packet is received on the dataObservable
  return merge(timer(200).pipe(mapTo(state.panelData), takeUntil(dataObservable)), dataObservable);
}
Example #29
Source File: customer.service.ts    From digital-bank-ui with Mozilla Public License 2.0 5 votes vote down vote up
fetchAllCustomers(): Observable<CustomerPage> {
    return this.http.get(`${this.baseUrl}/customers`).pipe(share());
  }