rxjs#asyncScheduler TypeScript Examples

The following examples show how to use rxjs#asyncScheduler. 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: emote.component.ts    From App with MIT License 6 votes vote down vote up
interactError = new Subject<string>().pipe(
		mergeMap(x => scheduled([
			of(!!x ? 'ERROR: ' + x : ''),
			timer(5000).pipe(
				takeUntil(this.interactError),
				mapTo('')
			)
		], asyncScheduler).pipe(mergeAll()))
	) as Subject<string>;
Example #2
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 #3
Source File: store-leaderboards.component.ts    From App with MIT License 6 votes vote down vote up
ngOnInit(): void {
		this.restService.egvault.Subscriptions.GetLeaderboards().pipe(
			RestService.onlyResponse(),
			map(res => this.gifts.next(res.body?.gift_subscriptions ?? [])),

			switchMap(() => scheduled([
				this.getPosition(1).pipe(tap(x => this.firstPlace = { user: x[0], count: x[1] })),
				this.getPosition(2).pipe(tap(x => this.secondPlace = { user: x[0], count: x[1] })),
				this.getPosition(3).pipe(tap(x => this.thirdPlace = { user: x[0], count: x[1] }))
			], asyncScheduler).pipe(mergeAll()))
		).subscribe({
			next: () => this.cdr.markForCheck()
		});
	}
Example #4
Source File: user-home.component.ts    From App with MIT License 6 votes vote down vote up
private shouldBlurEmote(emote: EmoteStructure): Observable<boolean> {
		return scheduled([
			emote.hasVisibility('HIDDEN'),
			emote.hasVisibility('PRIVATE')
		], asyncScheduler).pipe(
			concatAll(),
			toArray(),
			mergeMap(b => iif(() => b[0] === true || b[1] === true,
				this.clientService.hasPermission('EDIT_EMOTE_ALL').pipe(
					take(1),
					switchMap(bypass => iif(() => bypass,
						of(false),
						emote.getOwnerID().pipe(
							map(ownerID => ownerID !== this.clientService.id)
						)
					))
				),
				of(false)
			)),
			take(1)
		);
	}
Example #5
Source File: twitch-button.component.ts    From App with MIT License 6 votes vote down vote up
open(): void {
		scheduled([
			this.oauthService.openAuthorizeWindow<{ token: string }>().pipe(
				tap(data => this.clientService.setToken(data.token)),
				switchMap(() => this.restService.v2.GetUser('@me', { includeEditorIn: true }).pipe(
					map(res => this.clientService.pushData(res?.user ?? null))
				))
			),
			defer(() => this.oauthService.navigateTo(this.restService.v2.GetAuthURL()))
		], asyncScheduler).pipe(
			mergeAll(),
			switchMapTo(EMPTY)
		).subscribe({
			error: (err) => {
				this.dialogRef.open(ErrorDialogComponent, {
					data: {
						errorCode: err.status,
						errorMessage: err.error?.error ?? err.message,
						errorName: 'Could not sign in'
					} as ErrorDialogComponent.Data
				});
				this.logger.error('Could not sign in', err);
				this.clientService.logout();
				this.oauthService.openedWindow?.close();
			}
		});
	}
Example #6
Source File: utils.tsx    From ali-react-table with MIT License 6 votes vote down vote up
throttledWindowResize$ = defer(() =>
  fromEvent(window, 'resize', { passive: true }).pipe(
    throttleTime(150, asyncScheduler, { leading: true, trailing: true }),
  ),
)
Example #7
Source File: book.effects.ts    From router with MIT License 6 votes vote down vote up
search$ = createEffect(
    () =>
      ({ debounce = 300, scheduler = asyncScheduler } = {}) =>
        this.actions$.pipe(
          ofType(FindBookPageActions.searchBooks),
          debounceTime(debounce, scheduler),
          switchMap(({ query }) => {
            if (query === '') {
              return empty;
            }

            const nextSearch$ = this.actions$.pipe(
              ofType(FindBookPageActions.searchBooks),
              skip(1)
            );

            return this.googleBooks.searchBooks(query).pipe(
              takeUntil(nextSearch$),
              map((books: Book[]) => BooksApiActions.searchSuccess({ books })),
              catchError((err) =>
                of(BooksApiActions.searchFailure({ errorMsg: err.message }))
              )
            );
          })
        )
  );
Example #8
Source File: NcbiSummary.ts    From rcsb-saguaro-app with MIT License 6 votes vote down vote up
public static requestChromosomeData(chrId: string): Promise<ChromosomeMetadataInterface>{
        if(NcbiSummary.jobTask)
            NcbiSummary.jobTask.unsubscribe();
        const urlPrefix:string  = (resource as any).ncbi_summary_nuccore.url;
        const urlSuffix: string = (resource as any).ncbi_summary_nuccore.url_suffix;
        return new Promise<ChromosomeMetadataInterface>((resolve, reject)=>{
            const recursiveRequest = () =>{
                const url: string = urlPrefix+chrId+urlSuffix;
                const Http = new XMLHttpRequest();
                Http.timeout = NcbiSummary.httpTimeout;
                Http.open("GET", url);
                Http.send();
                Http.onloadend = (e) => {
                    if(Http.responseText.length == 0){
                        NcbiSummary.jobTask = asyncScheduler.schedule(()=>{
                            recursiveRequest();
                        },NcbiSummary.timeout);
                    }else {
                        const jsonResult: any = JSON.parse(Http.responseText);
                        const uid: string = (jsonResult as NcbiSummaryInterface)?.result?.uids[0];
                        const out: ChromosomeMetadataInterface = jsonResult.result[uid] as ChromosomeMetadataInterface;
                        out.ncbiId = chrId
                        resolve(out);
                    }
                };
                Http.onerror = (e) => {
                    if(NcbiSummary.jobTask)
                        NcbiSummary.jobTask.unsubscribe();
                    NcbiSummary.jobTask = asyncScheduler.schedule(()=>{
                        recursiveRequest();
                    },NcbiSummary.timeout);
                };
            };
            recursiveRequest();
        });
    }
Example #9
Source File: NcbiSummary.ts    From rcsb-saguaro-app with MIT License 6 votes vote down vote up
public static requestTaxonomyData(taxId: string): Promise<TaxonomyMetadataInterface>{
        if(NcbiSummary.jobTask)
            NcbiSummary.jobTask.unsubscribe();
        const urlPrefix:string  = (resource as any).ncbi_summary_taxonomy.url;
        const urlSuffix: string = (resource as any).ncbi_summary_taxonomy.url_suffix;
        return new Promise<TaxonomyMetadataInterface>((resolve, reject)=>{
            const recursiveRequest = () =>{
                const url: string = urlPrefix+taxId+urlSuffix;
                const Http = new XMLHttpRequest();
                Http.timeout = NcbiSummary.httpTimeout;
                Http.open("GET", url);
                Http.send();
                Http.onloadend = (e) => {
                    if(Http.responseText.length == 0){
                        NcbiSummary.jobTask = asyncScheduler.schedule(()=>{
                            recursiveRequest();
                        },NcbiSummary.timeout);
                    }else {
                        const jsonResult: any = JSON.parse(Http.responseText);
                        const uid: string = (jsonResult as NcbiSummaryInterface)?.result?.uids[0];
                        resolve(jsonResult.result[uid] as TaxonomyMetadataInterface);
                    }
                };
                Http.onerror = (e) => {
                    NcbiSummary.jobTask = asyncScheduler.schedule(()=>{
                        recursiveRequest();
                    },NcbiSummary.timeout);
                };
            };
            recursiveRequest();
        });
    }
Example #10
Source File: AbstractChartComponent.tsx    From rcsb-saguaro-app with MIT License 6 votes vote down vote up
private asyncUpdate(sqData: SearchQueryContextManagerSubjectInterface,x?:number): void {
        if(this.asyncSubscription)
            this.asyncSubscription.unsubscribe();
        this.asyncSubscription = asyncScheduler.schedule(()=>{
            this.setState({
                data:sqData.chartMap.get(this.props.attributeName).chart.data,
                subData:sqData.chartMap.get(this.props.attributeName).subChart?.data,
            });
        }, x );
    }
Example #11
Source File: PaginationItemComponent.tsx    From rcsb-saguaro-app with MIT License 6 votes vote down vote up
async execute(): Promise<void> {
        if(this.subscription) this.subscription.unsubscribe()
        this.subscription = asyncScheduler.schedule(async ()=>{
            const dom:[number,number] = this.props.pfv.getFv().getDomain()
            const sel: SelectionInterface[] = this.props.pfv.getFv().getSelection("select")
            await this.props.actionMethod.pfvMethod(
                this.props.elementId,
                ...this.props.actionMethod.pfvParams,
                {
                    ...this.props.actionMethod.additionalConfig,
                    page:{
                        after: this.state.after.toString(),
                        first: this.state.first
                    }
                }
            );
            this.props.pfv.getFv().setDomain(dom);
            this.props.pfv.getFv().setSelection({
                elements:sel.map((s)=>({
                    begin:s.rcsbFvTrackDataElement.begin,
                    end:s.rcsbFvTrackDataElement.end
                })),
                mode:"select"
            });
        },333);

    }
Example #12
Source File: RcsbFvAlignmentCollectorQueue.ts    From rcsb-saguaro-app with MIT License 6 votes vote down vote up
private recursiveExec(): void{
        if(this.taskQueue.length == 0){
            this.isQueueActive = false;
        }else{
            this.isQueueActive = true;
            this.workerList.filter(d=>d.available).forEach(aW=>{
                if(this.taskQueue.length > 0){
                    aW.available = false;
                    const task: TaskInterface = this.taskQueue.shift();
                    aW.worker.postMessage(task.request);
                    aW.worker.onmessage = (e) => {
                        task.callback(e.data);
                        aW.available = true;
                    }
                }
            });
            asyncScheduler.schedule(()=>{
                this.recursiveExec();
            },1000);
        }
    }
Example #13
Source File: emote-search.component.ts    From App with MIT License 5 votes vote down vote up
ngOnInit(): void {
		scheduled([
			this.form.get('query')?.valueChanges.pipe( // Look for changes to the name input form field
				mergeMap((value: string) => this.selectedSearchMode.pipe(take(1), map(mode => ({ mode, value })))),
				map(({ value, mode }) => ({ [mode.id]: value })) // Map SearchMode to value
			) ?? EMPTY,

			this.form.get('globalState')?.valueChanges.pipe( // Look for changes to the "show global"
				map((value: string) => ({ globalState: value }))
			) ?? EMPTY,

			this.form.get('channel')?.valueChanges.pipe(
				map((value: boolean) => ({ channel: value ? this.clientService.getSnapshot()?.login : '' }))
			) ?? EMPTY,
			this.form.get('zerowidth')?.valueChanges.pipe(
				map((value: boolean) => ({ filter: {
					visibility: value ? DataStructure.Emote.Visibility.ZERO_WIDTH : 0
				}}))
			) ?? EMPTY,

			this.form.get('sortBy')?.valueChanges.pipe(
				map((value: string) => ({ sortBy: value }))
			) ?? EMPTY,

			this.form.get('sortOrder')?.valueChanges.pipe(
				map((value: RestV2.GetEmotesOptions['sortOrder']) => ({ sortOrder: value }))
			) ?? EMPTY
		], asyncScheduler).pipe(
			mergeAll(),
			map(v => this.current = { ...this.current, ...v } as any),
			throttleTime(250)
		).subscribe({
			next: (v) => this.searchChange.next(v) // Emit the change
		});

		setTimeout(() => {
			if (!!this.defaultSearchOptions) {
				for (const k of Object.keys(this.form.getRawValue())) {
					const v = (this.defaultSearchOptions as any)[k as any];
					if (!v) {
						continue;
					}

					this.form.get(k)?.patchValue(v);
				}
			}
		}, 0);
	}
Example #14
Source File: user.component.ts    From App with MIT License 5 votes vote down vote up
ngOnInit(): void {
		this.route.paramMap.pipe(
			takeUntil(this.destroyed),
			map(params => params.get('user') as string),
			switchMap(id => this.restService.v2.GetUser(id, {
				includeEditors: true,
				includeEditorIn: true,
				includeOwnedEmotes: true,
				includeFullEmotes: true,
				includeAuditLogs: true,
				includeStreamData: true
			}, ['banned', 'youtube_id']).pipe(
				map(res => this.dataService.add('user', res.user)[0])
			)),
			tap(user => this.user.next(user)),
			switchMap(user => scheduled([
				user.getEditors().pipe(map(editors => this.editors.next(editors))),
				user.getEditorIn().pipe(map(edited => this.edited.next(edited))),
				user.getYouTubeID().pipe(tap(ytid => this.hasYouTube.next(ytid !== null)), switchMapTo(EMPTY))
			], asyncScheduler).pipe(concatAll(), mapTo(user))),
			tap(user => {
				const appURL = this.document.location.host + this.router.serializeUrl(this.router.createUrlTree(['/users', String(user.id)]));

				this.appService.pageTitleAttr.next([ // Update page title
					{ name: 'User', value: user.getSnapshot()?.display_name ?? '' }
				]);
				const roleName = user.getSnapshot()?.role?.name;
				const roleColor = user.getSnapshot()?.role?.color;
				const emoteCount = user.getSnapshot()?.emotes.length;
				const maxEmoteCount = user.getSnapshot()?.emote_slots;
				const displayName = user.getSnapshot()?.display_name ?? '';
				this.metaService.addTags([
					// { name: 'og:title', content: this.appService.pageTitle },
					// { name: 'og:site_name', content: this.appService.pageTitle },
					{ name: 'og:description', content: `${displayName} is${!!roleName ? ` ${roleName}` : ''} on 7TV with ${emoteCount}/${maxEmoteCount} emotes enabled`},
					{ name: 'og:image', content: user.getSnapshot()?.profile_image_url ?? '' },
					{ name: 'og:image:type', content: 'image/png' },
					{ name: 'theme-color', content: (roleColor ? `#${roleColor.toString(16)}` : '#fff') }
				]);

				if (!AppComponent.isBrowser.getValue()) {
					const link = this.document.createElement('link');
					link.setAttribute('type', 'application/json+oembed');

					const query = new URLSearchParams();
					query.append('object', Buffer.from(JSON.stringify({
						title: this.appService.pageTitle,
						author_name: displayName,
						author_url: `https://${appURL}`,
						provider_name: `7TV.APP - It's like a third party thing`,
						provider_url: 'https://7tv.app'
					})).toString('base64'));
					link.setAttribute('href', `https://${environment.origin}/services/oembed?` + query.toString());
					this.document.head.appendChild(link);
				}
			})
		).subscribe({
			error: (err) => this.loggerService.error('Couldn\'t fetch user', err)
		});
	}
Example #15
Source File: NcbiGenomeSequenceData.ts    From rcsb-saguaro-app with MIT License 5 votes vote down vote up
public static update(ncbiId: string, strand: number, reverse: boolean, trackWidth?: number): ((where: RcsbFvLocationViewInterface) => Promise<RcsbFvTrackData>) {
        let process: Subscription | null = null;
        return (where: RcsbFvLocationViewInterface) => {
            if(process)
                process.unsubscribe();
            return new Promise<RcsbFvTrackData>((resolve, reject) => {
                const delta: number = trackWidth ? trackWidth / (where.to - where.from) : 1000 / (where.to - where.from);
                if (delta > 4) {
                    let N: number = 0;
                    const timeout: number = 5000;
                    const getGenomeSequence: ()=>void = ()=> {
                        const Http = new XMLHttpRequest();
                        Http.timeout = timeout;
                        const url = NcbiGenomeSequenceData.urlPrefix + 'id=' + ncbiId + '&from=' + where.from + '&to=' + where.to + '&strand=' + strand + NcbiGenomeSequenceData.urlSuffix;
                        Http.open("GET", url);
                        Http.send();
                        Http.onloadend = (e) => {
                            const sequence: string = Http.responseText.split("\n").slice(1).join("");
                            if(sequence.length<1){
                                N++;
                                console.warn("HTTP error while access URL: " + url + " - empty sequence - "+ N);
                                if(N<4){
                                    process = asyncScheduler.schedule(()=>{
                                        getGenomeSequence();
                                    },timeout);
                                }else{
                                    reject("HTTP error while access URL: " + url + " - No more attempts after "+N);
                                }
                            }else {
                                const selectedOption: RcsbFvTrackData = [{
                                    begin: where.from,
                                    value: reverse ? sequence.split("").reverse().join("") : sequence
                                }];
                                resolve(selectedOption);
                            }
                        };
                        Http.onerror = (e) => {
                            N++;
                            console.warn("HTTP error while access URL: " + url + " - "+ N);
                            if(N<4){
                                process = asyncScheduler.schedule(()=>{
                                    getGenomeSequence();
                                },timeout);
                            }else{
                                reject("HTTP error while access URL: " + url + " - No more attempts after "+ N);
                            }

                        };
                    }
                    getGenomeSequence();
                } else {
                    resolve(null);
                }
            });
        };
    }