rxjs#asapScheduler TypeScript Examples

The following examples show how to use rxjs#asapScheduler. 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: app-shell.component.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
   * asapScheduler is used in order to avoid 'ExpressionChangedAfterItHasBeenCheckedError'.
   *
   * For some reason, if the router-outlet is placed inside a container with some structural directive,
   * the change detection gets somewhat messed up, resulting in the mentioned error.
   *
   * Example 1:
   * <ng-container *ngIf="...">
   *   <router-outlet #outlet=outlet (activate)="onRouteActivate(outlet.activatedRoute)"></router-outlet>
   * </ng-container>
   *
   * Example 2:
   * <ng-container *ngTemplateOutlet="template"></ng-container>
   * <ng-template #template>
   *   <router-outlet #outlet=outlet (activate)="onRouteActivate(outlet.activatedRoute)"></router-outlet>
   * </ng-template>
   */
  public onRouteActivate(route: ActivatedRoute): void {
    const isPageTitleVisible = Defined.orElse(route.snapshot.data['pageTitleVisible'], true);
    asapScheduler.schedule(() => this.pageTitle = isPageTitleVisible ? route.snapshot.data['pageTitle'] : null);
    this._routeActivate$.next();
  }
Example #2
Source File: emote-card.component.ts    From App with MIT License 6 votes vote down vote up
getBorderColor(): Observable<Color> {
		return scheduled([
			this.emote?.isGlobal().pipe(map(b => ({ b, type: 'global' }))),
			this.emote?.isChannel().pipe(map(b => ({ b, type: 'channel' }))),
		], asapScheduler).pipe(
			switchMap(value => value ?? EMPTY),
			filter(({ b }) => b === true),
			defaultIfEmpty({ b: false, type: 'none' }),
			take(1),
			map(o => o.type as 'global' | 'channel'),
			map(type => (type !== null ? ({
				global: this.globalBorderColor,
				channel: this.channelBorderColor
			})[type] as Color : this.borderColor))
		);
	}
Example #3
Source File: notify-button.component.ts    From App with MIT License 6 votes vote down vote up
ngOnInit(): void {
		scheduled([
			this.clientService.isAuthenticated().pipe(filter(ok => ok === true)),
			this.clientService.impersonating.pipe(mapTo(true))
		], asapScheduler).pipe(
			mergeAll(),
			switchMap(() => this.clientService.getActorUser()),
			switchMap(actor => actor.fetchNotificationCount()),
			tap(nCount => this.count.next(nCount))
		).subscribe();

		this.beginPolling();
	}
Example #4
Source File: client.service.ts    From App with MIT License 6 votes vote down vote up
canAccessAdminArea(): Observable<boolean> {
		return scheduled([
			this.hasPermission('MANAGE_REPORTS'),
			this.hasPermission('MANAGE_ROLES'),
			this.hasPermission('MANAGE_STACK'),
			this.hasPermission('MANAGE_USERS'),
			this.hasPermission('BAN_USERS')
		], asapScheduler).pipe(
			zipAll(),
			map(perms => perms.filter(b => b === true).length > 0)
		);
	}
Example #5
Source File: pdf.service.ts    From nestjs-pdf with MIT License 6 votes vote down vote up
toFile(
        template: string,
        filename: string,
        options?: PDFOptions,
        scheduler: SchedulerLike = asapScheduler,
    ): Observable<FileInfo> {
        return this.makeHtmlRender(template, options).pipe(
            mergeMap((html: string) => {
                const create = this.create(html, options);
                return bindNodeCallback<
                    [string | undefined],
                    [FileInfo]
                >(
                    create.toFile.bind(create),
                    scheduler,
                )(filename);
            }),
        );
    }
Example #6
Source File: pdf.service.ts    From nestjs-pdf with MIT License 6 votes vote down vote up
toStream(
        template: string,
        options?: PDFOptions,
        scheduler: SchedulerLike = asapScheduler,
    ): Observable<Readable> {
        return this.makeHtmlRender(template, options).pipe(
            mergeMap((html: string) => {
                const create = this.create(html, options);
                return bindNodeCallback<[], [Readable]>(
                    create.toStream.bind(create),
                    scheduler,
                )();
            }),
        );
    }
Example #7
Source File: pdf.service.ts    From nestjs-pdf with MIT License 6 votes vote down vote up
toBuffer(
        template: string,
        options?: PDFOptions,
        scheduler: SchedulerLike = asapScheduler,
    ): Observable<Buffer> {
        return this.makeHtmlRender(template, options).pipe(
            mergeMap((html: string) => {
                const create = this.create(html, options);
                return bindNodeCallback<[], [Buffer]>(
                    create.toBuffer.bind(create),
                    scheduler,
                )();
            }),
        );
    }
Example #8
Source File: pdf.service.ts    From nestjs-pdf with MIT License 6 votes vote down vote up
private generateHtmlFromTemplate(
        template: string,
        { engine, engineOptions }: ViewOptions,
        locals?: Record<string, any>,
    ): Observable<string> {
        return bindNodeCallback<
            [string, ViewOptions['engineOptions'] | undefined],
            [string]
        >(consolidate[engine], asapScheduler)(
            template,
            Object.assign({}, locals, engineOptions),
        );
    }
Example #9
Source File: chatterino-dialog.component.ts    From App with MIT License 5 votes vote down vote up
ngOnInit(): void {
		scheduled([
			this.restService.createRequest<ChatterinoDialogComponent.ChatterinoVersion>('get', '/chatterino/version/win/stable', {}, 'v2').pipe(
				RestService.onlyResponse(),
				map(res => {
					this.windowsDownloads.push(
						{ label: 'INSTALLER', url: res.body?.download ?? '' },
						{ label: 'PORTABLE / STANDALONE EXE', url: res.body?.portable_download ?? '' }
					);

					return {
						label: 'Windows', icon: 'windows', svgIcon: true,
						menu: this.installTypeMenu
					} as ChatterinoDialogComponent.PlatformIcon;
				})
			),

			this.restService.createRequest<ChatterinoDialogComponent.ChatterinoVersion>('get', '/chatterino/version/linux/stable', {}, 'v2').pipe(
				RestService.onlyResponse(),
				map(res => ({
					label: 'Linux', icon: 'linux', svgIcon: true,
					url: res.body?.download
				} as ChatterinoDialogComponent.PlatformIcon))
			),

			this.restService.createRequest<ChatterinoDialogComponent.ChatterinoVersion>('get', '/chatterino/version/macos/stable', {}, 'v2').pipe(
				RestService.onlyResponse(),
				map(res => ({
					label: 'MacOS', icon: 'apple', svgIcon: true,
					url: res.body?.download
				}))
			)
		], asapScheduler).pipe(
			concatAll()
		).subscribe({
			next: p => this.platforms.push(p)
		});

		this.platforms.push(
			{
				label: 'Nightly Build',
				icon: 'nightlight',
				url: 'https://github.com/SevenTV/chatterino7/releases/tag/nightly-build'
			}
		);
	}
Example #10
Source File: user-home.component.ts    From App with MIT License 5 votes vote down vote up
ngOnInit(): void {
		this.user.pipe(
			filter(user => !!user && AppComponent.isBrowser.getValue()),
			takeUntil(this.destroyed),
			tap(user => this.currentUser = user),
			tap(user => this.emoteSlots.next(user.getSnapshot()?.emote_slots ?? 0)),

			switchMap(user => user.getAuditEntries().pipe(
				tap(entries => this.auditEntries = entries),
				mapTo(user)
			)),
			switchMap(user => user.isLive().pipe(
				map(live => this.isLive.next(live)),
				switchMap(() => user.getBroadcast()),
				map(broadcast => this.broadcast.next(broadcast)),
				mapTo(user)
			)),
			switchMap(user => scheduled([
				user.getEmotes().pipe(map(emotes => ({ type: 'channel', emotes }))),
				user.getOwnedEmotes().pipe(map(emotes => ({ type: 'owned', emotes })))
			], asapScheduler).pipe(
				concatAll(),
				mergeMap(s => from(s.emotes).pipe(
					mergeMap(em => this.shouldBlurEmote(em).pipe(map(blur => ({ blur, emote: em })))),
					map(x => x.blur ? this.blurred.add(x.emote.getID()) : noop()),
					toArray(),
					mapTo(s)
				)),
				take(2),
			))
		).subscribe({
			next: set => {
				switch (set.type) {
					case 'channel':
						this.channelEmotes = set.emotes;
						this.channelCount.next(set.emotes.length);
						break;
					case 'owned':
						this.ownedEmotes = set.emotes;
						this.ownedCount.next(set.emotes.length);
						break;
				}
			}
		});
	}
Example #11
Source File: delay-on-microtask-queue.ts    From s-libs with MIT License 5 votes vote down vote up
/**
 * Delays the emission of items from the source Observable using the microtask queue.
 */
export function delayOnMicrotaskQueue<T>(): MonoTypeOperatorFunction<T> {
  return delay<T>(0, asapScheduler);
}
Example #12
Source File: module.e2e-spec.ts    From nestjs-pdf with MIT License 4 votes vote down vote up
describe('PDFModule', () => {
    let module: TestingModule;

    describe('register(...)', () => {
        let filename: string;
        let appService: AppService;

        beforeEach(async () => {
            module = await Test.createTestingModule({
                providers: [AppService],
                imports: [AppModule.withRegister()],
            }).compile();

            appService = module.get<AppService>(AppService);
        });

        it('should be defined', () => {
            expect(module.get<PDFService>(PDFService)).toBeDefined();
        });

        describe('toFile(...)', () => {
            it('toFile(template, filename, options, scheduler)', complete => {
                filename = join(tmpdir(), 'test.pdf');

                appService
                    .generatePDFToFile(
                        'test',
                        filename,
                        {
                            locals: { name: 'Toonday' },
                        },
                        asapScheduler,
                    )
                    .subscribe({
                        next(file: FileInfo) {
                            expect(file.filename).toBe(filename);
                            // Tests that file was actually created.
                            expect(() =>
                                rmFile(filename),
                            ).not.toThrowError();
                        },
                        complete,
                    });
            });

            it('toFile(template, filename, options, )', complete => {
                filename = join(tmpdir(), 'test.pdf');

                appService
                    .generatePDFToFile(
                        'test',
                        filename,
                        {
                            locals: { name: 'Toonday' },
                        },
                        undefined,
                    )
                    .subscribe({
                        next(file: FileInfo) {
                            expect(file.filename).toBe(filename);
                            // Tests that file was actually created.
                            expect(() =>
                                rmFile(filename),
                            ).not.toThrowError();
                        },
                        complete,
                    });
            });

            it('toFile(template, filename)', complete => {
                filename = join(tmpdir(), 'test.pdf');

                appService
                    .generatePDFToFile('test', filename, undefined)
                    .subscribe({
                        next(file: FileInfo) {
                            expect(file.filename).toBe(filename);
                            // Tests that file was actually created.
                            expect(() =>
                                rmFile(filename),
                            ).not.toThrowError();
                        },
                        complete,
                    });
            });
        });

        describe('toStream(...)', () => {
            it('toStream(template, options)', complete => {
                appService.generatePDFToStream('test', {}).subscribe({
                    next(stream: Readable) {
                        expect(stream instanceof Readable).toBe(true);
                    },
                    complete,
                });
            });

            it('toStream(template)', complete => {
                appService
                    .generatePDFToStream('test', undefined)
                    .subscribe({
                        next(stream: Readable) {
                            expect(stream instanceof Readable).toBe(
                                true,
                            );
                        },
                        complete,
                    });
            });
        });

        describe('toBuffer(...)', () => {
            it('toBuffer(template, options)', complete => {
                appService.generatePDFToBuffer('test', {}).subscribe({
                    next(buffer: Buffer) {
                        expect(Buffer.isBuffer(buffer)).toBe(true);
                    },
                    complete,
                });
            });

            it('toBuffer(template)', complete => {
                appService
                    .generatePDFToBuffer('test', undefined)
                    .subscribe({
                        next(buffer: Buffer) {
                            expect(Buffer.isBuffer(buffer)).toBe(
                                true,
                            );
                        },
                        complete,
                    });
            });
        });
    });

    describe('registerAsync(...)', () => {
        describe('useFactory(...)', () => {
            it('should register module', async () => {
                module = await Test.createTestingModule({
                    imports: [
                        AppModule.withUseFactoryRegisterAsync(),
                    ],
                }).compile();

                expect(
                    module.get<PDFService>(PDFService),
                ).toBeDefined();
            });
        });

        describe('useClass(...)', () => {
            it('should register module', async () => {
                module = await Test.createTestingModule({
                    imports: [AppModule.withUseClassRegisterAsync()],
                }).compile();

                expect(
                    module.get<PDFService>(PDFService),
                ).toBeDefined();
            });
        });

        describe('useExisting(...)', () => {
            it('should register module', async () => {
                module = await Test.createTestingModule({
                    imports: [
                        AppModule.withUseExistingRegisterAsync(),
                    ],
                }).compile();

                expect(
                    module.get<PDFService>(PDFService),
                ).toBeDefined();
            });
        });
    });
});