rxjs#Observer TypeScript Examples
The following examples show how to use
rxjs#Observer.
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: http-utils.ts From nativescript-http with MIT License | 7 votes |
export function processLocalFileRequest<T>(
url: string,
nsFileSystem: NSFileSystem,
successResponse: httpResponseFactory<T>,
errorResponse: httpErrorFactory): Observable<T> {
url = getAbsolutePath(url, nsFileSystem);
// request from local app resources
return new Observable((observer: Observer<T>) => {
if (nsFileSystem.fileExists(url)) {
const localFile = nsFileSystem.fileFromPath(url);
localFile.readText()
.then((data) => {
try {
const json = JSON.parse(data);
observer.next(successResponse(url, json, 200));
observer.complete();
} catch (error) {
// Even though the response status was 2xx, this is still an error.
// The parse error contains the text of the body that failed to parse.
const errorResult = { error, text: data };
observer.error(errorResponse(url, errorResult, 200));
}
}, (err: Object) => {
observer.error(errorResponse(url, err, 400));
});
} else {
observer.error(errorResponse(url, "Not Found", 404));
}
});
}
Example #2
Source File: client-disconnect.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
export async function connectToHost({symbolicName, disconnectOnUnloadDisabled = false, version = undefined}, observer: Observer<string>): Promise<void> { // eslint-disable-line @typescript-eslint/typedef
if (disconnectOnUnloadDisabled) {
Beans.register(MicrofrontendPlatformStopper, {useClass: NullMicrofrontendPlatformStopper});
}
if (version) {
Beans.register(VERSION, {useValue: version});
}
await MicrofrontendPlatform.connectToHost(symbolicName);
observer.next(Beans.get(ɵBrokerGateway).brokerInfo.clientId);
}
Example #3
Source File: index.ts From TidGi-Desktop with Mozilla Public License 2.0 | 6 votes |
private readonly getWorkerObserver = (resolve: () => void, reject: (error: Error) => void): Observer<IGitLogMessage> => ({
next: (messageObject) => {
const { message, meta, level } = messageObject;
if (typeof meta === 'object' && meta !== null && 'step' in meta) {
this.popGitErrorNotificationToUser((meta as { step: GitStep }).step, message);
}
logger.log(level, this.translateMessage(message), meta);
},
error: (error) => {
this.translateAndLogErrorMessage(error as Error);
reject(error as Error);
},
complete: () => resolve(),
});
Example #4
Source File: orders.component.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 6 votes |
convertBase64(inputValue: any) {
return Observable.create((observer: Observer<string>) => {
// create an image object
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = inputValue;
if (!img.complete) {
// This will call another method that will create image from url
img.onload = () => {
observer.next(this.getBase64Image(img));
observer.complete();
};
img.onerror = err => {
observer.error(err);
};
} else {
observer.next(this.getBase64Image(img));
observer.complete();
}
});
}
Example #5
Source File: orderdetail.component.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 6 votes |
convertBase64(inputValue: any) {
return Observable.create((observer: Observer<string>) => {
// create an image object
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = inputValue;
if (!img.complete) {
// This will call another method that will create image from url
img.onload = () => {
observer.next(this.getBase64Image(img));
observer.complete();
};
img.onerror = err => {
observer.error(err);
};
} else {
observer.next(this.getBase64Image(img));
observer.complete();
}
});
}
Example #6
Source File: vieworders.component.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 6 votes |
convertBase64(inputValue: any) {
return Observable.create((observer: Observer<string>) => {
// create an image object
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = inputValue;
if (!img.complete) {
// This will call another method that will create image from url
img.onload = () => {
observer.next(this.getBase64Image(img));
observer.complete();
};
img.onerror = err => {
observer.error(err);
};
} else {
observer.next(this.getBase64Image(img));
observer.complete();
}
});
}
Example #7
Source File: create-operator-function.ts From s-libs with MIT License | 6 votes |
/**
* Use this to create a complex pipeable operator. It is usually better style to compose existing operators than to create a brand new one, but when you need full control this can reduce some boilerplate.
*
* The supplied `subscriber` will act as a simple pass-through of all values, errors, and completion to `destination`. Modify it for your needs.
*
* A simple example, recreating the "map" operator:
* ```ts
* function map<I, O>(fn: (input: I) => O) {
* return createOperatorFunction<I, O>(
* (subscriber, destination) => {
* subscriber.next = (value) => {
* destination.next(fn(value));
* };
* },
* );
* }
* ```
*
* For a more complex example, check the source of `skipAfter`.
*/
export function createOperatorFunction<
SourceType,
DestinationType = SourceType,
>(
modifySubscriber: (
subscriber: RequiredSubscriber<SourceType>,
destination: Observer<DestinationType>,
) => void,
): OperatorFunction<SourceType, DestinationType> {
return (source: Observable<SourceType>): Observable<DestinationType> =>
new Observable<DestinationType>((destination) => {
const subscriber = new Subscriber<SourceType>(destination);
modifySubscriber(subscriber, destination);
return source.subscribe(subscriber);
});
}
Example #8
Source File: LocalAuthenticationDataSource.ts From rn-clean-architecture-template with MIT License | 6 votes |
getToken(): Observable<string> {
return Observable.create(async (observer: Observer<string>) => {
try {
const result = await Keychain.getGenericPassword();
if (result) {
observer.next(result.password);
observer.complete();
return;
}
observer.error(new LocalException({}));
} catch (error) {
observer.error(new LocalException(error));
}
});
}
Example #9
Source File: LocalAuthenticationDataSource.ts From rn-clean-architecture-template with MIT License | 6 votes |
saveToken(username: string, token: string): Observable<boolean> {
return Observable.create(async (observer: Observer<boolean>) => {
try {
await Keychain.setGenericPassword(username, token);
observer.next(true);
observer.complete();
} catch (error) {
observer.error(new LocalException(error));
}
});
}
Example #10
Source File: RxRemoteProvider.ts From rn-clean-architecture-template with MIT License | 6 votes |
request<T>(requestConfig: AxiosRequestConfig): Observable<AxiosResponse<T>> {
return Observable.create(async (observer: Observer<AxiosResponse<T>>) => {
try {
const result = await this.axiosInstance.request(requestConfig);
observer.next(result);
observer.complete();
} catch (error) {
observer.error(new RxAxiosProviderException(error));
}
});
}
Example #11
Source File: MetricService.ts From viewer-components-react with MIT License | 6 votes |
public getDefaultMetricsForSensor$(sensor: Sensor, enableIPIMetricFilters = false): Observable<Metric[]> {
return new Observable<Metric[]>((observer: Observer<Metric[]>) => {
const sensorType = EntityTypeService.getType(EntityType.SENSOR, sensor.getType() as string);
const defaultMetrics = sensorType.getDefaultMetrics();
if (defaultMetrics.length) {
observer.next(
_map(defaultMetrics, (metric: {id: string, unit: string}) => new Metric(metric.id, metric.id, metric.unit))
);
observer.complete();
} else {
this.getMetrics$([sensor.getId()], enableIPIMetricFilters)
.pipe(
map((metricCategories: MetricCategory[]) => {
const firstMetricCategory = _find(metricCategories, (c: MetricCategory) => !!c.getMetrics().length);
if (firstMetricCategory) {
return firstMetricCategory.getMetrics()[0];
} else {
return null;
}
})
)
.subscribe({
next: (metric: Metric | null) => {
if (metric) {
observer.next([metric]);
observer.complete();
} else {
observer.error({ code: "no-metrics-found" });
}
},
error: (error: any) => observer.error(error),
});
}
});
}
Example #12
Source File: SocketService.ts From viewer-components-react with MIT License | 6 votes |
public send$(request: string, params: {[key: string]: any} = {}, unsubscribeRequest?: string): Observable<any> {
return AuthService.authState$()
.pipe(
filter((authState: AuthState | null) => !!authState),
first(),
switchMap((authState: AuthState | null) => {
return new Observable<any>((observer: Observer<any>) => {
// Generate a random request id for this message
const id = _random(50000, 99999999);
// Add project ids parameter to request
params.projectIds = [authState?.getProjectId()];
// Save the stream reference so we can find it later on incoming messages
const newStream: SocketStream = { id, request, params, observer };
this.streams[id] = newStream;
// Send the message once socket is connected
// Also, if not connected, start the connection process
this.connect();
this.sendSocketMessage(id, request, params);
// Delete stream from map after observable completes
return () => {
if (unsubscribeRequest) {
this.send$(unsubscribeRequest, { id: newStream.id }).subscribe();
}
delete this.streams[newStream.id];
};
});
})
);
}
Example #13
Source File: client-connect.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
export async function connectToHost({symbolicName, brokerDiscoverTimeout, connectCount}, observer: Observer<string>): Promise<void> { // eslint-disable-line @typescript-eslint/typedef
await MicrofrontendPlatform.connectToHost(symbolicName, {brokerDiscoverTimeout});
observer.next(Beans.get(ɵBrokerGateway).brokerInfo.clientId);
for (let i = 1; i < connectCount; i++) {
const {clientId} = await Beans.get(ɵBrokerGateway).connectToBroker();
observer.next(clientId);
}
}
Example #14
Source File: gift-card-storage.ts From bitpay-browser-extension with MIT License | 6 votes |
createEventSourceObservable = async ({
invoiceId,
user
}: {
invoiceId: string;
user?: BitpayUser;
}): Promise<Observable<Invoice>> => {
const busUrl = await getBusUrl({ invoiceId, user });
return Observable.create((observer: Observer<Invoice>) => {
const source = new EventSource(busUrl);
source.addEventListener('statechange', (event: Event) => {
const { data } = event as CustomEvent;
const updatedInvoice = JSON.parse(data);
observer.next(updatedInvoice);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
source.addEventListener('error', (event: any) => observer.error(event));
return (): void => {
source.close();
};
});
}
Example #15
Source File: context-service.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
/**
* Looks up the context tree for a value associated with the given name.
*
* @param name - The name of the value to return.
* @param options - Options to control context lookup.
* @return An Observable that emits the context value associated with the given key and then completes.
* When the requested value is not found in a context, the Observable emits `null` and then completes.
*/
private lookupContextValue$<T>(name: string, options?: ContextLookupOptions): Observable<T | T[] | null> {
return new Observable((observer: Observer<T | T[] | null>): TeardownLogic => {
const replyTo = UUID.randomUUID();
const unsubscribe$ = new Subject<void>();
const contextValueLookupRequest = Contexts.newContextValueLookupRequest(name, replyTo, options);
// Wait until the reply is received.
Beans.get(MessageClient).observe$<T | T[] | null | undefined>(replyTo)
.pipe(
take(1),
map(reply => reply.headers.get(MessageHeaders.Status) === ResponseStatusCodes.OK ? (reply.body ?? null) : null),
takeUntil(unsubscribe$),
)
.subscribe(observer);
// Send the request.
Promise.all([whenSubscribedToReplyTopic(replyTo), this._whenContextTreeChangeListenerInstalled])
.then(() => window.parent.postMessage(contextValueLookupRequest, '*'))
.catch(error => observer.error(error));
return (): void => unsubscribe$.next();
});
}
Example #16
Source File: context-service.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
/**
* Looks up the context names of all values registered in the current and parent contexts.
*
* @return An Observable that emits the names of all values registered in the current and parent contexts and then completes.
*/
private lookupContextNames$(): Observable<Set<string>> {
return new Observable((observer: Observer<Set<string>>): TeardownLogic => {
const replyTo = UUID.randomUUID();
const unsubscribe$ = new Subject<void>();
const contextNamesLookupRequest = Contexts.newContextTreeNamesLookupRequest(replyTo);
// Wait until the reply is received.
Beans.get(MessageClient).observe$<Set<string>>(replyTo)
.pipe(
take(1),
map(reply => reply.headers.get(MessageHeaders.Status) === ResponseStatusCodes.OK ? reply.body! : new Set<string>()),
takeUntil(unsubscribe$),
)
.subscribe(observer);
// Send the request.
Promise.all([whenSubscribedToReplyTopic(replyTo), this._whenContextTreeChangeListenerInstalled])
.then(() => window.parent.postMessage(contextNamesLookupRequest, '*'))
.catch(error => observer.error(error));
return (): void => unsubscribe$.next();
});
}
Example #17
Source File: broker-gateway.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
public requestReply$<T = any>(channel: MessagingChannel, message: IntentMessage | TopicMessage): Observable<TopicMessage<T>> {
return new Observable((observer: Observer<TopicMessage>): TeardownLogic => {
if (isPlatformStopped()) {
observer.error(GatewayErrors.PLATFORM_STOPPED_ERROR);
return noop;
}
const replyTo = UUID.randomUUID();
const unsubscribe$ = new Subject<void>();
const requestError$ = new Subject<never>();
// Add 'ReplyTo' topic to the message headers where to receive the response(s).
message.headers.set(MessageHeaders.ReplyTo, replyTo);
// Receive replies sent to the reply topic.
merge(this.subscribeToTopic$<T>(replyTo), requestError$)
.pipe(takeUntil(merge(this._platformStopping$, unsubscribe$)))
.subscribe({
next: reply => observer.next(reply),
error: error => observer.error(error),
complete: noop, // As per the API, the Observable never completes.
});
// Post the request to the broker.
this.postMessage(channel, message)
.catch(error => requestError$.error(error));
return (): void => unsubscribe$.next();
});
}
Example #18
Source File: broker-gateway.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
public subscribeToTopic$<T>(topic: string): Observable<TopicMessage<T>> {
return new Observable((observer: Observer<TopicMessage>): TeardownLogic => {
if (isPlatformStopped()) {
observer.error(GatewayErrors.PLATFORM_STOPPED_ERROR);
return noop;
}
const subscriberId = UUID.randomUUID();
const unsubscribe$ = new Subject<void>();
const subscribeError$ = new Subject<never>();
// Receive messages sent to the given topic.
merge(this.message$, subscribeError$)
.pipe(
filterByChannel<TopicMessage>(MessagingChannel.Topic),
filterByMessageHeader({key: MessageHeaders.ɵTopicSubscriberId, value: subscriberId}),
pluckMessage(),
takeUntil(merge(this._platformStopping$, unsubscribe$)),
finalize(() => this.unsubscribeFromTopic(topic, subscriberId)),
)
.subscribe({
next: reply => observer.next(reply),
error: error => observer.error(error),
complete: noop, // As per the API, the Observable never completes.
});
// Post the topic subscription to the broker.
const topicSubscribeMessage: TopicSubscribeCommand = {subscriberId, topic, headers: new Map()};
this.postMessage(MessagingChannel.TopicSubscribe, topicSubscribeMessage)
.catch(error => subscribeError$.error(error));
return (): void => unsubscribe$.next();
});
}
Example #19
Source File: microfrontend-fixture.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export function testcase_11(params: Dictionary, observer: Observer<any>): void {
observer.next(params);
}
Example #20
Source File: client-disconnect.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export async function connectToHostThenStopPlatform({symbolicName}, observer: Observer<string>): Promise<void> { // eslint-disable-line @typescript-eslint/typedef
await MicrofrontendPlatform.connectToHost(symbolicName);
observer.next(Beans.get(ɵBrokerGateway).brokerInfo.clientId);
await MicrofrontendPlatform.destroy();
}
Example #21
Source File: client-disconnect.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export async function connectToHostThenLocationHref({symbolicName, locationHref}, observer: Observer<string>): Promise<void> { // eslint-disable-line @typescript-eslint/typedef
await MicrofrontendPlatform.connectToHost(symbolicName);
observer.next(Beans.get(ɵBrokerGateway).brokerInfo.clientId);
window.location.href = locationHref;
}
Example #22
Source File: microfrontend-fixture.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export function testcase_2(params: Dictionary, observer: Observer<string>): void {
observer.next('a');
observer.next('b');
observer.next('c');
observer.complete();
}
Example #23
Source File: microfrontend-fixture.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export function testcase_3(params: Dictionary, observer: Observer<never>): void {
observer.error('ERROR FROM SCRIPT');
}
Example #24
Source File: ObservationService.ts From viewer-components-react with MIT License | 5 votes |
private getAllObservationsForSensor$(sensor: Sensor, observationQuery: ObservationQuery): Observable<ObservationSet> {
return new Observable<ObservationSet>((observer: Observer<ObservationSet>) => {
let observationSet: ObservationSet;
// We first need to prime the metrics cache so we have
// metric metadata, then proceed to observation retrieval
MetricService.primeMetricCache$(sensor.getId(), observationQuery.getMetric() as string)
.pipe(
switchMap(() => {
observationSet = this.createObservationSet(sensor, observationQuery);
return SocketService.send$(this.socketEndpoints.getObservations, {
sensor: sensor.getId(),
metric: observationQuery.getMetric(),
unit: observationQuery.getUnit(),
params: this.getMetricParamsForQuery(observationQuery),
startDate: observationQuery.getStartDate(),
endDate: observationQuery.getEndDate(),
limit: observationQuery.getLimitFunction(),
smoothing: observationQuery.getDataAveragingFunction(),
}).pipe(
startWith({}),
tap((data: any) => {
if (data.data) {
_forEach(data.data, (value: number, date: string) => {
observationSet.addObservation([Date.parse(date), value]);
});
}
})
);
})
)
.subscribe({
error: () => {
observer.next(this.createObservationSet(sensor, observationQuery));
observer.complete();
},
complete: () => {
observationSet.sortObservations();
LoggerService.log("Received observations:", observationSet);
observer.next(observationSet);
observer.complete();
},
});
});
}
Example #25
Source File: microfrontend-fixture.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export function testcase_5(params: Dictionary, observer: Observer<void>): void {
observer.complete();
}
Example #26
Source File: EntityDataService.ts From viewer-components-react with MIT License | 5 votes |
// Convenience method for retrieving observations for selected sensor (for graphs)
public getObservationsForSelectedSensor$(
observationQueryMetadata?: ObservationQueryMetadata
): Observable<{loading: boolean, data: SensorData | undefined}> {
return new Observable<{loading: boolean, data: SensorData | undefined}>(
(observer: Observer<{loading: boolean, data: SensorData | undefined}>) => {
// Subscribe to data for sensor, including new observations
const dataSubscription = this.getSelectedSensorId$()
.pipe(
switchMap((selectedEntityId: string | undefined) => {
if (selectedEntityId) {
return EntityService.getEntity$(EntityType.SENSOR, selectedEntityId)
.pipe(
switchMap((entity: any) => {
return ObservationService.getFirstReadingDateForSensor$(selectedEntityId)
.pipe(
switchMap((firstReadingDate: string | undefined) => {
return this.getObservationQueriesForSensor$(
selectedEntityId,
true
).pipe(
switchMap((queries: ObservationQuery[]) => {
observer.next({loading: true, data: undefined});
return ObservationService.getObservations$(
entity,
queries[0],
observationQueryMetadata
).pipe(
map((observations: ObservationSet | null) => {
return {
sensor: entity,
observations: observations ? [observations] : [],
firstReadingDate,
};
})
);
})
);
})
);
})
);
} else {
return of(undefined);
}
})
)
.subscribe({
next: (data: SensorData | undefined) => {
observer.next({loading: false, data});
},
error: (error: any) => {
observer.error(error);
},
complete: () => {
observer.complete();
},
});
// Make sur we close any outstanding data subscription when observable completes
return () => {
dataSubscription.unsubscribe();
};
}
);
}
Example #27
Source File: SocketService.ts From viewer-components-react with MIT License | 5 votes |
private connect(): void {
if (this.state$.getValue() === SocketState.DISCONNECTED) {
this.state$.next(SocketState.CONNECTING);
ConfigService.getSocketApi$()
.pipe(
switchMap((socketApi: string) => {
return AuthService.authState$()
.pipe(
filter((authState: AuthState | null) => !!authState),
first(),
map((authState: AuthState | null) => {
return { socketApi, authState: authState as AuthState };
})
);
})
)
.subscribe((connectionInfo: {socketApi: string, authState: AuthState}) => {
// Connect socket to specified API (based on environment)
this.socket = new WebSocket(connectionInfo.socketApi);
// Register socket event handlers
this.socket.onopen = () => {
LoggerService.log("Socket opened with:", connectionInfo.socketApi);
// Perform authenticate request immediately after connection
new Observable<any>((observer: Observer<any>) => {
// Save the stream reference so we can find it later on incoming messages
this.streams[0] = {
id: 0,
request: "authenticate",
params: { code: connectionInfo.authState.getApiKey() },
observer,
};
// Send the message over socket
this.socket?.send(JSON.stringify({
jsonrpc: this.jsonRpcSpec,
id: this.streams[0].id,
method: this.streams[0].request,
params: this.streams[0].params,
}));
}).subscribe(
() => {
LoggerService.log("Socket authenticated!");
this.state$.next(SocketState.CONNECTED);
this.startConnectionTimer();
delete this.streams[0];
}
);
};
this.socket.onmessage = (event: any) => {
this.onMessage(event.data);
};
this.socket.onerror = (error: any) => {
LoggerService.log("Received general socket error:", error);
};
this.socket.onclose = () => {
this.onClose();
};
});
}
}
Example #28
Source File: microfrontend-fixture.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export function testcase_7(params: Dictionary, observer: Observer<MatcherResult>): void {
observer.next(new TopicMatcher('a/b/c').match('a/b/c')); // {TopicMatcher} is a project-specific type
}
Example #29
Source File: microfrontend-fixture.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
export function testcase_8(params: Dictionary, observer: Observer<string>): void {
observer.next(UUID.randomUUID()); // {UUID} is provided by `@scion/toolkit`
}