rxjs/operators#takeWhile TypeScript Examples
The following examples show how to use
rxjs/operators#takeWhile.
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: jobs.component.ts From RcloneNg with MIT License | 6 votes |
ngOnInit(): void {
const outer = this;
this.visable = true;
this.listGroup$ = new (class extends ListGroupFlow {
public prerequest$ = combineLatest([
outer.listTrigger,
outer.cmdService.listCmd$.verify(this.cmd),
]).pipe(map(([, node]) => node));
})();
this.listGroup$.deploy();
this.listGroup$.getOutput().subscribe(x => {
this.refreshing = false;
if (x[1].length !== 0) return;
this.groups = x[0].groups;
});
this.refreshing = true;
this.listTrigger.next(1);
this.stats$ = new (class extends CoreStatsFlow {
public prerequest$ = combineLatest([
outer.cmdService.rst$.getOutput(),
outer.statsTrigger,
outer.cmdService.listCmd$.verify(this.cmd),
]).pipe(
takeWhile(() => outer.visable),
map(
([, group, node]): CombErr<CoreStatsFlowInNode> => {
if (node[1].length !== 0) return [{}, node[1]] as any;
if (group === '') return node;
return [{ ...node[0], group }, []];
}
)
);
})();
this.stats$.deploy();
this.statsTrigger.next('');
}
Example #2
Source File: home.component.ts From Angular-Cookbook with MIT License | 6 votes |
startStream() {
const streamSource = interval(1500);
const secondStreamSource = interval(3000);
const fastestStreamSource = interval(500);
this.streamsOutput$ = merge(
streamSource,
secondStreamSource,
fastestStreamSource
).pipe(
takeWhile(() => !!this.isComponentAlive),
map((output) => {
console.log(output);
this.outputStreamData = [...this.outputStreamData, output];
return this.outputStreamData;
})
);
}
Example #3
Source File: progress-monitor.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
/**
* Splits this monitor into separate child monitors for breaking down this monitor's work into smaller units.
*
* Each child monitor contributes to the overall progress of this monitor. The ratio allows child monitors to be
* weighted differently, for example, one child monitor can contribute twice as much as another to the overall progress.
* After all child monitors reported "done", this monitor will also enter "done".
*/
public split(...ratio: number[]): ProgressMonitor[] {
if (this._hasSubMonitors) {
throw Error('[IllegalMonitorStateError] Monitor cannot be split multiple times.');
}
this._hasSubMonitors = true;
const subMonitors = ratio.map(() => new ProgressMonitor());
combineLatest(subMonitors.map(subMonitor => subMonitor._progress$))
.pipe(
computeProgress(ratio),
takeWhile(progress => progress < 1, true),
takeUntil(this._done$),
)
.subscribe(progress => {
this._progress$.next(progress);
});
return subMonitors;
}
Example #4
Source File: bind.plugin.ts From ng-event-plugins with Apache License 2.0 | 6 votes |
addEventListener(
element: HTMLElement & Record<string, Observable<unknown>>,
event: string,
): Function {
element[event] = element[event] || EMPTY;
const method = this.getMethod(element, event);
const zone$ = this.manager.getZone().onStable;
const sub = concat(
zone$.pipe(takeWhile(() => element[event] === EMPTY)),
defer(() => element[event]),
).subscribe(method);
return () => sub.unsubscribe();
}
Example #5
Source File: auth.component.ts From ngx-admin-dotnet-starter with MIT License | 6 votes |
// showcase of how to use the onAuthenticationChange method
constructor(protected auth: NbAuthService, protected location: Location) {
this.subscription = auth.onAuthenticationChange()
.pipe(takeWhile(() => this.alive))
.subscribe((authenticated: boolean) => {
this.authenticated = authenticated;
});
}
Example #6
Source File: account-activity.component.ts From digital-bank-ui with Mozilla Public License 2.0 | 6 votes |
constructor(
private themeService: NbThemeService,
private userActivityService: UserActivityData,
) {
this.themeService
.getJsTheme()
.pipe(takeWhile(() => this.alive))
.subscribe((theme) => {
this.currentTheme = theme.name;
});
this.getUserActivity(this.type);
}
Example #7
Source File: api.service.ts From storm with MIT License | 6 votes |
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
// Catch 401 errors and ask for the API key.
// Redo the request with the provided API key in basic auth headers
catchError((err: ApiException) => {
if (err.status != 401) {
return throwError(err)
}
return this.ask$.pipe(
switchMap(key => {
const withAuthHeaderReq = req.clone({
headers: req.headers.set('Authorization', 'Basic ' + btoa(':' + key))
});
return next.handle(withAuthHeaderReq)
})
)
}),
// Keep retrying 401 errors
retryWhen(errors => errors.pipe(
takeWhile((err: ApiException) => err.status === 401)
))
)
}
Example #8
Source File: login.component.ts From Angular-Cookbook with MIT License | 5 votes |
ngOnInit(): void {
this.isComponentAlive = true;
this.loginForm.valueChanges
.pipe(takeWhile(() => this.isComponentAlive))
.subscribe(() => {
this.formSubmitSuccess = false;
});
}
Example #9
Source File: messaging.model.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
/**
* 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 #10
Source File: state.service.ts From ngx-admin-dotnet-starter with MIT License | 5 votes |
constructor(directionService: NbLayoutDirectionService) {
directionService.onDirectionChange()
.pipe(takeWhile(() => this.alive))
.subscribe(direction => this.updateSidebarIcons(direction));
this.updateSidebarIcons(directionService.getDirection());
}
Example #11
Source File: generate-auto-extractors.spec.ts From js-client with MIT License | 5 votes |
describe('generateAutoExtractors()', () => {
const generateAutoExtractors = makeGenerateAutoExtractors(TEST_BASE_API_CONTEXT);
// Use a randomly generated tag, so that we know exactly what we're going to query
const tag = uuidv4();
// The number of entries to generate
const count = 1000;
// The start date for generated queries
const start = new Date(2010, 0, 0);
// The end date for generated queries; one minute between each entry
const end = addMinutes(start, count - 1);
beforeAll(async () => {
// Generate and ingest some entries
const ingestJSONEntries = makeIngestJSONEntries(TEST_BASE_API_CONTEXT);
const values: Array<CreatableJSONEntry> = range(0, count).map(i => {
const timestamp = addMinutes(start, i).toISOString();
return {
timestamp,
tag,
data: JSON.stringify({ timestamp, value: i }, null, 2), // Add vertical whitespace, so that JSON is recommended over CSV
};
});
await ingestJSONEntries(values);
// Check the list of tags until our new tag appears
const getAllTags = makeGetAllTags(TEST_BASE_API_CONTEXT);
while (!(await getAllTags()).includes(tag)) {
// Give the backend a moment to catch up
await sleep(1000);
}
}, 25000);
it(
'Should generate auto extractors',
integrationTest(async () => {
const subscribeToOneSearch = makeSubscribeToOneSearch(TEST_BASE_API_CONTEXT);
const query = `tag=${tag} limit 10`;
const search = await subscribeToOneSearch(query, { filter: { dateRange: { start, end } } });
const entries = await lastValueFrom(
search.entries$.pipe(
map(e => e as RawSearchEntries),
takeWhile(e => !e.finished, true),
),
);
const exploreResults = await generateAutoExtractors({ tag, entries });
expect(Object.keys(exploreResults).length).withContext('we should get >0 AX suggestions').toBeGreaterThan(0);
expect(exploreResults['json']).withContext('we should have a JSON AX suggestion').toBeDefined();
expect(exploreResults['json'].length).withContext('we should have >0 JSON AX suggestions').toBeGreaterThan(0);
exploreResults['json'].forEach(ax => {
expect(ax.autoExtractor.tag).withContext('the suggested AX tag should match the provided tag').toEqual(tag);
expect(ax.autoExtractor.module).withContext('the suggested AX module should be json').toEqual('json');
expect(ax.confidence).withContext('json is the right module, so its confidence should be 10').toEqual(10);
expect(ax.autoExtractor.parameters)
.withContext('the suggested AX module should break out the fields in the entries')
.toEqual('timestamp value');
expect(ax.explorerEntries.length).withContext('explore should have >0 elements').toBeGreaterThan(0);
ax.explorerEntries.forEach(exploreEntry => {
expect(exploreEntry.elements.length)
.withContext('explore should have two elements: one for each field (timestamp and value)')
.toEqual(2);
exploreEntry.elements.forEach(elt => {
expect(elt.filters.length).withContext('we should have filters on explore elements').toBeGreaterThan(0);
});
});
});
// We can't really make assertions about what the other AX generators are going to do when we look at JSON data
}),
25000,
);
});
Example #12
Source File: account-activity.component.ts From digital-bank-ui with Mozilla Public License 2.0 | 5 votes |
getUserActivity(period: string) {
this.userActivityService
.getUserActivityData(period)
.pipe(takeWhile(() => this.alive))
.subscribe((userActivityData) => {
this.userActivity = userActivityData;
});
}