rxjs#defer TypeScript Examples

The following examples show how to use rxjs#defer. 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 vote down vote up
/**
 * 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: ApiService.ts    From argo-react with MIT License 6 votes vote down vote up
maintainProject = (id: any, body: any): Observable<any> => {
  return defer(() => {
    return from<Promise<any>>(
      fetch(`${config.urls.API_URL}/project/changeStateToMaintained/${id}`, {
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          Authorization: `Bearer ${localStorage.getItem("jwt-token")}`,
        },
        method: "PUT",
        body: JSON.stringify(body),
      }).then((res) => res.json()),
    );
  });
}
Example #3
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public eventCount = (id: string, event: string) =>
    defer(() =>
      from(
        request(`/jetlinks/device/instance/${id}/event/${event}?format=true`, {
          method: 'GET',
          params: encodeQueryParam({
            pageSize: 1,
          }),
        }),
      ).pipe(
        filter(resp => resp.status === 200),
        map(resp => resp.result.total),
      ),
    );
Example #4
Source File: ethereum-polygon-bridge.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public depositTradeAfterCheckpoint(
    burnTransactionHash: string,
    onTransactionHash: (hash: string) => void
  ): Observable<TransactionReceipt> {
    const maticPOSClient = new MaticPOSClient({
      network: 'mainnet',
      version: 'v1',
      maticProvider: networks.find(n => n.name === BLOCKCHAIN_NAME.POLYGON).rpcLink,
      parentProvider: this.walletConnectorService.web3
    });
    const walletAddress = this.authService.userAddress;

    const onTradeTransactionHash = async (hash: string) => {
      if (onTransactionHash) {
        onTransactionHash(hash);
      }
      await this.bridgeApiService.patchPolygonTransaction(
        burnTransactionHash,
        hash,
        TRANSACTION_STATUS.WITHDRAW_IN_PROGRESS
      );
    };

    return defer(async () => {
      const receipt = await maticPOSClient.exitERC20(burnTransactionHash, {
        from: walletAddress,
        onTransactionHash: onTradeTransactionHash
      });
      await this.bridgeApiService.patchPolygonTransaction(
        burnTransactionHash,
        receipt.transactionHash,
        TRANSACTION_STATUS.COMPLETED
      );
      return receipt;
    });
  }
Example #5
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public getRuleInstanceList = (deviceId: any, data: any) => defer(
        () => from(request(`/jetlinks/edge/operations/${deviceId}/rule-instance-list/invoke`, {
            method: 'POST',
            data: data
        }))
            .pipe(
                filter(resp => resp.status === 200),
                map(resp => resp.result[0])
            ));
Example #6
Source File: fetch.ts    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
/** Use REST to fetch the children for a node */
function fetchNonRealtime(
  realtimeRef: firebase.database.Reference,
  query: QueryParams
): Observable<string[]> {
  const params = getRestQueryParams(query);
  const shallow = restUrl(realtimeRef, { ...params, shallow: 'true' });
  return defer(() => fetch(shallow, { headers: ADMIN_AUTH_HEADERS })).pipe(
    map((r) => r.json()),
    map((data) => Object.keys(data))
  );
}
Example #7
Source File: BleTransport.ts    From Elastos.Essentials.App with MIT License 6 votes vote down vote up
// TODO we probably will do this at end of open
  async inferMTU() {
    let { mtu } = this.device;
    await this.exchangeAtomicImpl(async () => {
      Logger.log(TAG, "inferMTU exchangeAtomicImpl");
      try {
        mtu =
          (await merge(
            this.notifyObservable.pipe(
              first((buffer) => buffer.readUInt8(0) === 0x08),
              map((buffer) => buffer.readUInt8(5))
            ),
            defer(() => from(this.write(Buffer.from([0x08, 0, 0, 0, 0])))).pipe(
              ignoreElements()
            )
          ).toPromise()) + 3;
      } catch (e: any) {
        Logger.log(TAG, "inferMTU got error:", String(e));
        await bleManager.disconnect(this.id).catch(() => {}); // but we ignore if disconnect worked.

        throw remapError(e);
      }
    });

    if (mtu > 23) {
      const mtuSize = mtu - 3;
      this.mtuSize = mtuSize;
    }

    return this.mtuSize;
  }
Example #8
Source File: auth.state.ts    From auth0-angular with MIT License 6 votes vote down vote up
/**
   * Trigger used to pull User information from the Auth0Client.
   * Triggers when an event occurs that needs to retrigger the User Profile information.
   * Events: Login, Access Token change and Logout
   */
  private readonly isAuthenticatedTrigger$ = this.isLoading$.pipe(
    filter((loading) => !loading),
    distinctUntilChanged(),
    switchMap(() =>
      // To track the value of isAuthenticated over time, we need to merge:
      //  - the current value
      //  - the value whenever the access token changes. (this should always be true of there is an access token
      //    but it is safer to pass this through this.auth0Client.isAuthenticated() nevertheless)
      //  - the value whenever refreshState$ emits
      merge(
        defer(() => this.auth0Client.isAuthenticated()),
        this.accessTokenTrigger$.pipe(
          mergeMap(() => this.auth0Client.isAuthenticated())
        ),
        this.refresh$.pipe(mergeMap(() => this.auth0Client.isAuthenticated()))
      )
    )
  );
Example #9
Source File: ApiService.ts    From argo-react with MIT License 6 votes vote down vote up
getPinataPinDetails = (id: any): Observable<any> => {
  return defer(() => {
    return from<Promise<any>>(
      fetch(`${config.urls.API_URL}/deploymentData/pinata/pins/${id}`, {
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          Authorization: `Bearer ${localStorage.getItem("jwt-token")}`,
        },
        method: "GET",
      }).then((res) => res.json()),
    );
  });
}
Example #10
Source File: share-popover.page.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
private presentToastCopied() {
    return defer(() => (this.toastCtrl.create({
      message: '連結已複製到剪貼簿',
      position: 'top',
      color: 'primary',
      cssClass: 'toast',
      duration: 1000,
    })))
      .pipe(
        switchMap(toast => toast.present()),
      );
  }
Example #11
Source File: app.service.ts    From App with MIT License 6 votes vote down vote up
updateSubscriptionData(): void {
		// EgVault - Payment API State
		scheduled([
			this.restService.egvault.Root().pipe(
				RestService.onlyResponse(),
				tap(() => this.egvaultOK.next(true)),
				catchError(() => defer(() => this.egvaultOK.next(false)))
			),
			this.restService.awaitAuth().pipe(
				filter(ok => ok === true),
				switchMap(() => this.restService.egvault.Subscriptions.Get('@me').pipe(RestService.onlyResponse())),
				tap(res => {
					if (!res.body?.subscription) {
						this.subscription.next(null);
						return undefined;
					}

					res.body.subscription.renew = res.body.renew;
					res.body.subscription.ending_at = new Date(res.body.end_at);
					this.subscription.next(res.body.subscription);
					return undefined;
				}),
				mapTo(undefined)
			)
		], asyncScheduler).pipe(mergeAll()).subscribe({
			error: err => console.error(err)
		});
	}
Example #12
Source File: ɵmanifest-registry.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
private installIntentionsLookupRequestHandler(): void {
    Beans.get(MessageClient).observe$<ManifestObjectFilter>(ManifestRegistryTopics.LookupIntentions)
      .pipe(takeUntil(this._destroy$))
      .subscribe((request: TopicMessage<ManifestObjectFilter>) => runSafe(() => {
        const replyTo = request.headers.get(MessageHeaders.ReplyTo);
        const lookupFilter = request.body || {};

        const finder$ = defer(() => of(this._intentionStore.find(lookupFilter)));
        return finder$
          .pipe(
            expand(() => this._intentionStore.change$.pipe(take(1), mergeMap(() => finder$))),
            distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
            takeUntilUnsubscribe(replyTo),
          )
          .subscribe(intentions => { // eslint-disable-line rxjs/no-nested-subscribe
            Beans.get(MessageClient).publish<Intention[]>(replyTo, intentions, {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.OK)});
          });
      }));
  }
Example #13
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public getSceneList = (deviceId: any, data: any) => defer(
        () => from(request(`/jetlinks/edge/operations/${deviceId}/rule-engine-scene-list/invoke`, {
            method: 'POST',
            data: data
        }))
            .pipe(
                filter(resp => resp.status === 200),
                map(resp => resp.result[0])
            ));
Example #14
Source File: popover.service.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
private presentPopover(popover: HTMLIonPopoverElement, dismissTime?: number): Observable<any> {
    const manualDismiss$ = defer(() => popover.present())
      .pipe(
        switchMap(() => from(popover.onDidDismiss())),
      );
    const autoDismiss$ = defer(() => popover.present())
      .pipe(
        delay(dismissTime),
        switchMap(() => popover.dismiss()),
      );
    return (dismissTime) ? autoDismiss$ : manualDismiss$;
  }
Example #15
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public startScene = (deviceId: any, data: any) => defer(
        () => from(request(`/jetlinks/edge/operations/${deviceId}/rule-engine-scene-start/invoke`, {
            method: 'POST',
            data: data
        }))
            .pipe(
                filter(resp => resp.status === 200),
                map(resp => resp.result[0])
            ));
Example #16
Source File: modal.service.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
showShopScannerModal(): Observable<any> {
    return defer(() => this.modalCtrl.create({
      component: ShopScannerComponent,
      animated: true,
      backdropDismiss: false,
    }))
      .pipe(
        switchMap(modal => this.presentModal(modal)),
      );
  }
Example #17
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public executeScene = (deviceId: any, data: any) => defer(
        () => from(request(`/jetlinks/edge/operations/${deviceId}/rule-engine-scene-execute/invoke`, {
            method: 'POST',
            data: data
        }))
            .pipe(
                filter(resp => resp.status === 200),
                map(resp => resp.result[0])
            ));
Example #18
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
manifest$ = merge(
  ...Object.entries({
    "**/*.scss": stylesheets$,
    "**/*.ts*":  javascripts$
  })
    .map(([pattern, observable$]) => (
      defer(() => process.argv.includes("--watch")
        ? watch(pattern, { cwd: "src" })
        : EMPTY
      )
        .pipe(
          startWith("*"),
          switchMapTo(observable$.pipe(toArray()))
        )
    ))
)
  .pipe(
    scan((prev, mapping) => (
      mapping.reduce((next, [key, value]) => (
        next.set(key, value.replace(`${base}/`, ""))
      ), prev)
    ), new Map<string, string>()),
  )
Example #19
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public getNotifierTemplateList = (deviceId: any, data: any) => defer(
        () => from(request(`/jetlinks/edge/operations/${deviceId}/notifier-template-list/invoke`, {
            method: 'POST',
            data: data
        }))
            .pipe(
                filter(resp => resp.status === 200),
                map(resp => resp.result[0])
            ));
Example #20
Source File: carousel.component.ts    From canopy with Apache License 2.0 6 votes vote down vote up
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 #21
Source File: service.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
public getInstanceDetail = (deviceId: string, id: string) => defer(
        () => from(request(`/jetlinks/edge/operations/${deviceId}/device-instance-detail/invoke`, {
            method: 'POST',
            data: {
                deviceId: id
            }
        })).pipe(
            filter(resp => resp.status === 200),
            map(resp => resp.result[0])
        ))
Example #22
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
emojis$ = defer(() => resolve("venv/**/twemoji_db.py"))
  .pipe(
    switchMap(file => read(file)),
    map(data => {
      const [, payload] = data.match(/^emoji = ({.*})$.alias/ms)!
      return Object.entries<TwemojiIcon>(JSON.parse(payload))
        .reduce((index, [name, { unicode }]) => index.set(
          name.replace(/(^:|:$)/g, ""),
          `${unicode}.svg`
        ), new Map<string, string>())
    })
  )