rxjs#ReplaySubject TypeScript Examples
The following examples show how to use
rxjs#ReplaySubject.
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 gnosis.1inch.exchange with MIT License | 7 votes |
export class RefreshingReplaySubject<T> extends ReplaySubject<T> {
private providerCallback: () => Observable<T>;
private lastProviderTrigger: number;
private readonly windowTime;
constructor(providerCallback: () => Observable<T>, windowTime?: number) {
// Cache exactly 1 item forever in the ReplaySubject
super(1);
this.windowTime = windowTime || 60000;
this.lastProviderTrigger = 0;
this.providerCallback = providerCallback;
}
public _subscribe(subscriber: Subscriber<T>): Subscription {
// Hook into the subscribe method to trigger refreshing
this._triggerProviderIfRequired();
return super._subscribe(subscriber);
}
protected _triggerProviderIfRequired() {
const now = this._getNow();
if ((now - this.lastProviderTrigger) > this.windowTime) {
// Data considered stale, provider triggering required...
this.lastProviderTrigger = now;
this.providerCallback().pipe(first()).subscribe((t: T) => this.next(t));
}
}
}
Example #2
Source File: component-creator.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
async createOnBody<T = any>(component: Type<T>): Promise<{
component: ComponentRef<T>;
open: () => void;
close: () => Promise<any>,
destroyed$: ReplaySubject<void>
}> {
const componentRef = this.componentFactoryResolver
.resolveComponentFactory(component)
.create(this.injector);
const responseObject = {
destroyed$: new ReplaySubject<void>(),
close: () => {
return new Promise(resolve => {
this.ngZone.run(() => {
this.appRef.detachView(componentRef.hostView);
componentRef.onDestroy(() => {
responseObject.destroyed$.next();
responseObject.destroyed$.complete();
resolve(true);
});
componentRef.destroy();
});
});
},
open: () => {
this.ngZone.run(() => {
this.appRef.attachView(componentRef.hostView);
const rootNode = (componentRef.hostView as EmbeddedViewRef<ApplicationRef>).rootNodes[0] as HTMLElement;
this.renderer.appendChild(this.document.body, rootNode);
});
},
component: componentRef,
};
return responseObject;
}
Example #3
Source File: screen-media-query.service.ts From ng-devui-admin with MIT License | 6 votes |
// 可以传入一个基准point,返回数据结构{ currentPoint, 变大or变小or没变,比基准point大or小or一样 }
public getPoint(): ReplaySubject<{ currentPoint: DaBreakpoint; change: number; compare: { [key: string]: number } }> {
if (!this.currentPoint) {
this.currentPoint = this.getCurrentPoint()!;
this.pointChangeSub.next({
currentPoint: this.currentPoint,
change: 0,
compare: this.comparePoints(this.currentPoint),
});
fromEvent(window, 'resize')
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
const tempPoint = this.getCurrentPoint()!;
if (this.currentPoint !== tempPoint) {
const change = this.comparePoints(tempPoint, this.currentPoint) as number;
this.currentPoint = tempPoint;
this.pointChangeSub.next({
currentPoint: this.currentPoint,
change: change,
compare: this.comparePoints(tempPoint),
});
}
});
}
return this.pointChangeSub;
}
Example #4
Source File: operators.ts From alauda-ui with MIT License | 6 votes |
publishRef = <T>(bufferSizeOrConfig: PublishRefConfig<T> = {}) => {
const {
bufferSize = 1,
windowTime,
timestampProvider,
connector = () =>
new ReplaySubject(bufferSize, windowTime, timestampProvider),
resetOnError = false,
resetOnComplete = false,
resetOnRefCountZero = true,
} = typeof bufferSizeOrConfig === 'number'
? ({
bufferSize: bufferSizeOrConfig,
} as Exclude<PublishRefConfig<T>, number>)
: bufferSizeOrConfig;
return share<T>({
connector,
resetOnError,
resetOnComplete,
resetOnRefCountZero,
});
}
Example #5
Source File: fetch.ts From firebase-tools-ui with Apache License 2.0 | 6 votes |
/**
* Creates an observable view model and query subject. The view model will
* update when the query emits/changes.
*/
export function createViewModel(
ref: firebase.database.Reference,
canDoRealtime$: Observable<boolean>
) {
const query = new ReplaySubject<QueryParams>(1);
query.next({ limit: DEFAULT_PAGE_SIZE });
const viewModel$ = query.pipe(
switchMap((queryParams) => {
return canDoRealtime$.pipe(
concatMap((realtime) =>
realtime
? realtimeToViewModel(ref, queryParams)
: nonRealtimeToViewModel(ref, queryParams)
)
);
})
);
return { query, viewModel$ };
}
Example #6
Source File: rx-operators.ts From ionic-pwa-example-moment with MIT License | 6 votes |
export function beforeEach<T, V>(valueBefore: V) {
return (source$: Observable<T>) =>
defer(() => {
const subject$ = new ReplaySubject<V | T>(1);
source$
.pipe(
// Force the source values emitted asynchronizingly.
delay(0)
)
.subscribe({
next: v => {
subject$.next(valueBefore);
subject$.next(v);
},
error: (err: unknown) => subject$.error(err),
complete: () => subject$.complete(),
});
return subject$.pipe(
// Make sure the values emitted asynchronizingly.
concatMap(v => of(v).pipe(delay(0)))
);
});
}
Example #7
Source File: cache.ts From s-libs with MIT License | 6 votes |
/**
* 1. Caches the last value emitted to give to new subscribers (without running any upstream pipe operators)
* 2. Manages all subscribers directly, without passing subscriptions up the stream.
*
* This is very similar to `shareReplay(1)`, except that once all subscribers unsubscribe this also unsubscribes from the upstream observable.
*
* ```ts
* const source = new BehaviorSubject(1000);
* const result = source.pipe(expensiveComputation(), cache());
* source.subscribe(); // expensiveComputation(1000) runs
* source.subscribe(); // the cached result is used
* source.next(2000); // expensiveComputation(2000) runs once, emitted to both subscribers
* ```
*/
export function cache<T>(): MonoTypeOperatorFunction<T> {
return (source: Observable<T>): Observable<T> => {
let middleMan: ReplaySubject<T> | undefined;
let upstreamSubscription: Subscription;
return new Observable<T>((subscriber) => {
if (!middleMan) {
middleMan = new ReplaySubject<T>(1);
upstreamSubscription = source.subscribe(middleMan);
}
const subscription = middleMan.subscribe(subscriber);
// teardown logic
return (): void => {
subscription.unsubscribe();
if (middleMan!.observers.length === 0) {
upstreamSubscription.unsubscribe();
middleMan = undefined;
}
};
});
};
}
Example #8
Source File: facet-timeline.component.ts From sba-angular with MIT License | 6 votes |
/**
* Given a combined aggregation configuration and a range, this method searches for the most
* adapted aggregation scale (years, months, weeks or days) and updates the data if necessary.
* @param config
* @param range
* @param iTimeseries
*/
updateCombinedAggregation(config: TimelineCombinedAggregations, range: [Date, Date], timeseries$: ReplaySubject<TimelineSeries>) {
const nmonths = d3.timeMonth.count(range[0], range[1]);
if(!config.maxNMonths || config.maxNMonths.length !== config.aggregations.length) {
console.error(config);
throw new Error("maxNMonths and aggregations must have the same number of items");
}
// Find the aggregation with min maxNMonths with maxNMonths >= nmonths
let jMin;
config.maxNMonths.forEach((maxNMonths, j) => {
if(maxNMonths >= nmonths && (jMin === undefined || maxNMonths < config.maxNMonths[jMin] || config.maxNMonths[jMin] === -1)
|| maxNMonths === -1 && jMin === undefined){
jMin = j;
}
});
const bestAggregation = config.aggregations[jMin];
if(bestAggregation !== config.current
|| this.currentRange && (range[0] < this.currentRange[0] || range[1] > this.currentRange[1])) {
config.current = bestAggregation;
this.getTimeseries(bestAggregation, range).subscribe({
next: d => timeseries$.next(d),
error: err => timeseries$.error(err)
});
}
}
Example #9
Source File: exercise.ts From typescript-exercises with MIT License | 6 votes |
export function createExercise(exerciseNumber: number) {
if (!exercisesCache[exerciseNumber]) {
const localStorageKey = `exercise.${exerciseNumber}`;
const exerciseOriginalFiles = exerciseStructures[exerciseNumber];
let files = localData.get(localStorageKey, {} as FileContents);
const saveToLocalStorage = debounce(() => {
localData.set(localStorageKey, files);
}, 500);
const subject = new ReplaySubject<FileTree>(1);
subject.next(createModifiedFileTree(files, exerciseOriginalFiles));
exercisesCache[exerciseNumber] = {
observable$: subject,
update(filename: string, code: string) {
files = {...files, [filename]: code};
saveToLocalStorage();
subject.next(createModifiedFileTree(files, exerciseOriginalFiles));
},
revert(filename: string) {
files = {...files};
delete files[filename];
saveToLocalStorage();
subject.next(createModifiedFileTree(files, exerciseOriginalFiles));
}
};
}
return exercisesCache[exerciseNumber];
}
Example #10
Source File: background.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 5 votes |
connectedPort$: ReplaySubject<chrome.runtime.Port> = new ReplaySubject<chrome.runtime.Port>();
Example #11
Source File: personalize.service.ts From ng-devui-admin with MIT License | 5 votes |
private _themeChange = new ReplaySubject<any>(1);
Example #12
Source File: componentCreator.ts From ngx-dynamic-hooks with MIT License | 5 votes |
// Component creation
// ----------------------------------------------------------------------------------------------------------------
/**
* Takes a hook along with a DOM node and loads the specified component class (normal or lazy-loaded).
* Returns a subject the emits the component class when ready.
*
* @param componentConfig - The componentConfig from HookData
*/
loadComponentClass(componentConfig: ComponentConfig): ReplaySubject<new(...args: any[]) => any> {
const componentClassLoaded: ReplaySubject<new(...args: any[]) => any> = new ReplaySubject(1);
// a) If is normal class
if (componentConfig.hasOwnProperty('prototype')) {
componentClassLoaded.next(componentConfig as (new(...args: any[]) => any));
// b) If is LazyLoadComponentConfig
} else if (componentConfig.hasOwnProperty('importPromise') && componentConfig.hasOwnProperty('importName')) {
// Catch typical importPromise error
if ((componentConfig as LazyLoadComponentConfig).importPromise instanceof Promise) {
throw Error(`When lazy-loading a component, the "importPromise"-field must contain a function returning the import-promise, but it contained the promise itself.`);
}
// Warning if using old Angular version
const ngVersion = this.platform.getNgVersion();
if (ngVersion < 9 && isDevMode()) {
console.warn('It seems you are trying to use lazy-loaded-components with an Angular version older than 9. Please note that this functionality requires the new Ivy renderer to be enabled.');
}
(componentConfig as LazyLoadComponentConfig).importPromise().then((m) => {
const importName = (componentConfig as LazyLoadComponentConfig).importName;
const compClass = m.hasOwnProperty(importName) ? m[importName] : m['default'];
componentClassLoaded.next(compClass);
});
} else {
throw Error('The "component" property of a returned HookData object must either contain the component class or a LazyLoadComponentConfig');
}
return componentClassLoaded;
}
Example #13
Source File: activated-route.mock.ts From Angular-Cookbook with MIT License | 5 votes |
// Use a ReplaySubject to share previous values with subscribers
// and pump new values into the `paramMap` observable
private subject = new ReplaySubject<ParamMap>();
Example #14
Source File: grocy-api.component.ts From pantry_party with Apache License 2.0 | 5 votes |
private ngUnsubscribe = new ReplaySubject<true>();
Example #15
Source File: data-studio.service.ts From visualization with MIT License | 5 votes |
private readonly markdown$ = new ReplaySubject<string>();
Example #16
Source File: dependent-intentions.component.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
private _appChange$ = new ReplaySubject<void>(1);
Example #17
Source File: electron.service.ts From WowUp with GNU General Public License v3.0 | 5 votes |
private readonly _appUpdateSrc = new ReplaySubject<AppUpdateEvent>();
Example #18
Source File: loader.service.ts From nghacks with MIT License | 5 votes |
private _onProgressbarVisibilityChange: ReplaySubject<boolean> = new ReplaySubject<boolean>();
Example #19
Source File: autocomplete.component.ts From alauda-ui with MIT License | 5 votes |
directive$$ = new ReplaySubject<AutoCompleteDirective>(1);
Example #20
Source File: auth.service.ts From auth0-angular with MIT License | 5 votes |
private appStateSubject$ = new ReplaySubject<TAppState>(1);
Example #21
Source File: dlc-file.service.ts From bitcoin-s-ts with MIT License | 5 votes |
private offer: Subject<OfferWithHex|null> = new ReplaySubject()
Example #22
Source File: json-schema-form.component.ts From json-schema-form with Apache License 2.0 | 5 votes |
/**
* choices that might be loaded async, initialized with current value and its potentially delayed toString value
*/
choices: ReplaySubject<Choice[]>;
Example #23
Source File: autocomplete.component.ts From geonetwork-ui with GNU General Public License v2.0 | 5 votes |
selectionSubject = new ReplaySubject<MatAutocompleteSelectedEvent>(1)
Example #24
Source File: city-ranking.service.ts From avid-covider with MIT License | 5 votes |
ranking = new ReplaySubject<any[]>(1);
Example #25
Source File: analyzer-config.service.ts From IntelOwl-ng with GNU Affero General Public License v3.0 | 5 votes |
private _analyzersList$: ReplaySubject<IAnalyzersList> = new ReplaySubject(1);
Example #26
Source File: grafana.service.ts From models-web-app with Apache License 2.0 | 5 votes |
public serviceInitializedSuccessfully$ = new ReplaySubject<boolean>(1);
Example #27
Source File: single-spa-props.ts From qiankun with MIT License | 5 votes |
singleSpaPropsSubject = new ReplaySubject<SingleSpaProps>(1)
Example #28
Source File: angular.ts From dayz-server-manager with MIT License | 5 votes |
// Use a ReplaySubject to share previous values with subscribers
// and pump new values into the `paramMap` observable
private subject = new ReplaySubject<ParamMap>();
Example #29
Source File: capture-item.component.ts From capture-lite with GNU General Public License v3.0 | 5 votes |
private readonly proof$ = new ReplaySubject<Proof>(1);