本文整理汇总了TypeScript中rxjs.ReplaySubject.pipe方法的典型用法代码示例。如果您正苦于以下问题:TypeScript ReplaySubject.pipe方法的具体用法?TypeScript ReplaySubject.pipe怎么用?TypeScript ReplaySubject.pipe使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rxjs.ReplaySubject
的用法示例。
在下文中一共展示了ReplaySubject.pipe方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: brightness
function brightness(value: number): void {
brightnessSubject.pipe(take(1)).subscribe(v => {
v = Math.max(Math.min(v + value, 100), 0);
showBrightness(v);
brightnessSubject.next(v);
});
}
示例2: PeriodBuffer
/**
* Create single PeriodBuffer Observable:
* - Lazily create (or reuse) a SourceBuffer for the given type.
* - Create a Buffer linked to an Adaptation each time it changes, to
* download and append the corresponding Segments in the SourceBuffer.
* - Announce when the Buffer is full or is awaiting new Segments through
* events
* @returns {Observable}
*/
export default function PeriodBuffer({
abrManager,
bufferType,
clock$,
content,
garbageCollectors,
segmentBookkeepers,
segmentPipelinesManager,
sourceBuffersManager,
options,
wantedBufferAhead$,
} : IPeriodBufferArguments) : Observable<IPeriodBufferEvent> {
const { period } = content;
// Emits the chosen adaptation for the current type.
const adaptation$ = new ReplaySubject<Adaptation|null>(1);
return adaptation$.pipe(
switchMap((adaptation) => {
if (adaptation == null) {
log.info(`Buffer: Set no ${bufferType} Adaptation`, period);
const previousQSourceBuffer = sourceBuffersManager.get(bufferType);
let cleanBuffer$ : Observable<unknown>;
if (previousQSourceBuffer != null) {
log.info(`Buffer: Clearing previous ${bufferType} SourceBuffer`);
cleanBuffer$ = previousQSourceBuffer
.removeBuffer(period.start, period.end || Infinity);
} else {
cleanBuffer$ = observableOf(null);
}
return observableConcat<IPeriodBufferEvent>(
cleanBuffer$.pipe(mapTo(EVENTS.adaptationChange(bufferType, null, period))),
createFakeBuffer(clock$, wantedBufferAhead$, bufferType, { period })
);
}
log.info(`Buffer: Updating ${bufferType} adaptation`, adaptation, period);
const newBuffer$ = clock$.pipe(
take(1),
mergeMap((tick) => {
const qSourceBuffer = createOrReuseQueuedSourceBuffer(
sourceBuffersManager, bufferType, adaptation, options);
const strategy = getAdaptationSwitchStrategy(
qSourceBuffer.getBuffered(), period, bufferType, tick);
if (strategy.type === "needs-reload") {
return observableOf(EVENTS.needsMediaSourceReload());
}
const cleanBuffer$ = strategy.type === "clean-buffer" ?
observableConcat(
...strategy.value.map(({ start, end }) =>
qSourceBuffer.removeBuffer(start, end)
)).pipe(ignoreElements()) : EMPTY;
const bufferGarbageCollector$ = garbageCollectors.get(qSourceBuffer);
const adaptationBuffer$ = createAdaptationBuffer(adaptation, qSourceBuffer);
return observableConcat(
cleanBuffer$,
observableMerge(adaptationBuffer$, bufferGarbageCollector$)
);
}));
return observableConcat<IPeriodBufferEvent>(
observableOf(EVENTS.adaptationChange(bufferType, adaptation, period)),
newBuffer$
);
}),
startWith(EVENTS.periodBufferReady(bufferType, period, adaptation$))
);
/**
* @param {string} bufferType
* @param {Object} period
* @param {Object} adaptation
* @param {Object} qSourceBuffer
* @returns {Observable}
*/
function createAdaptationBuffer<T>(
adaptation : Adaptation,
qSourceBuffer : QueuedSourceBuffer<T>
) : Observable<IAdaptationBufferEvent<T>|IBufferWarningEvent> {
const { manifest } = content;
const segmentBookkeeper = segmentBookkeepers.get(qSourceBuffer);
const pipelineOptions = getPipelineOptions(
bufferType, options.segmentRetry, options.offlineRetry);
const pipeline = segmentPipelinesManager
.createPipeline(bufferType, pipelineOptions);
//.........这里部分代码省略.........
示例3: tap
tap(data => authenticatedUser.next(data.currentUser)),
catchError(() => {
authenticatedUser.next(null)
return []
}),
mergeMap(() => [])
)
}
const initialSiteConfigAuthPublic = window.context.site['auth.public']
/**
* Whether auth is required to perform any action.
*
* If an HTTP request might be triggered by an unauthenticated user on a server with auth.public ==
* false, the caller must first check authRequired. If authRequired is true, then the component must
* not initiate the HTTP request. This prevents the browser's devtools console from showing HTTP 401
* errors, which mislead the user into thinking there is a problem (and make debugging any actual
* issue much harder).
*/
export const authRequired = authenticatedUser.pipe(map(user => user === null && !initialSiteConfigAuthPublic))
// Populate authenticatedUser.
if (window.context.isAuthenticatedUser) {
refreshAuthenticatedUser()
.toPromise()
.then(() => void 0, err => console.error(err))
} else {
authenticatedUser.next(null)
}
示例4: constructor
constructor($args: { mqttUrl: string; name: string }, $log: Ha4usLogger) {
const url = new URL($args.mqttUrl)
$log.info(
`Connecting to ${url.protocol}//${url.username}@${url.host} as ${
$args.name
}`
)
const mqtt = Mqtt.connect(
$args.mqttUrl,
{
clientId:
$args.name +
'_' +
Math.random()
.toString(16)
.substr(2, 8),
rejectUnauthorized: false,
will: {
topic: $args.name + '/connected',
payload: '0',
qos: 0,
retain: true,
},
}
)
mqtt.once('connect', () => {
this.connected = 1
this.$log.info('Connected as %s', mqtt.options.clientId)
})
mqtt.on('error', function (err) {
$log.error('Error mqtt', err)
})
mqtt.on('close', function () {
$log.warn('closing mqtt')
})
super(mqtt)
this.mqtt = mqtt
this.$log = $log
this.caching$ = new ReplaySubject(1)
this.cache$ = this.caching$.pipe(
distinct(), // only add if not already in there
mergeMap(topic => this.observe(topic)), // observe the new topic
scan((acc: Map<string, Ha4usMessage>, msg: Ha4usMessage) => {
acc.set(msg.topic, msg)
return acc
}, new Map<string, Ha4usMessage>()),
shareReplay()
)
this.cache$.subscribe(cache => {
debug(`cache updated ( size: ${cache.size})`)
this.cache = cache
})
this.domain = $args.name
}
示例5: run
//.........这里部分代码省略.........
const doc = uri && documents.get(uri);
const docSettings = doc && await getSettingsToUseForDocument(doc) || undefined;
const settings = await getActiveUriSettings(uri);
return {
languageEnabled: languageId && doc ? await isLanguageEnabled(doc, settings) : undefined,
fileEnabled: uri ? !await isUriExcluded(uri) : undefined,
settings,
docSettings,
};
});
function textToWords(text: string): string[] {
const setOfWords = new Set(
Text.extractWordsFromCode(text)
.map(t => t.text)
.map(t => t.toLowerCase())
);
return [...setOfWords];
}
connection.onRequest(methodNames.splitTextIntoWords, (text: string): Api.SplitTextIntoWordsResult => {
return {
words: textToWords(text),
};
});
interface DocSettingPair {
doc: TextDocument;
settings: CSpellUserSettings;
}
// validate documents
const disposableValidate = validationRequestStream
.pipe(filter(doc => !validationByDoc.has(doc.uri)))
.subscribe(doc => {
if (!validationByDoc.has(doc.uri)) {
const uri = doc.uri;
if (isUriBlackListed(uri)) {
validationByDoc.set(doc.uri, validationRequestStream.pipe(
filter(doc => uri === doc.uri),
take(1),
tap(doc => log('Ignoring:', doc.uri)),
).subscribe()
);
} else {
validationByDoc.set(doc.uri, validationRequestStream.pipe(
filter(doc => uri === doc.uri),
tap(doc => log('Request Validate:', doc.uri)),
debounceTime(50),
tap(doc => log('Request Validate 2:', doc.uri)),
flatMap(async doc => ({ doc, settings: await getActiveSettings(doc) }) as DocSettingPair),
debounce(dsp => timer(dsp.settings.spellCheckDelayMs || defaultDebounce)
.pipe(filter(() => !isValidationBusy))
),
flatMap(validateTextDocument),
).subscribe(diag => connection.sendDiagnostics(diag))
);
}
}
});
const disposableTriggerUpdateConfigStream = triggerUpdateConfig.pipe(
tap(() => log('Trigger Update Config')),
debounceTime(100),
).subscribe(() => {
updateActiveSettings();
示例6: from
interface Display extends DisplayIdentifier, DisplayBrightness {
identifier: string;
}
export {Display, DisplayBrightness, DisplayIdentifier};
export {brightness};
const brightnessSubject = new ReplaySubject<number>(1);
const brightnessSubscription = brightnessSubject
.pipe(
debounceTime(510),
distinctUntilChanged(),
switchMap(v => {
return from(
Promise.all([
applyExternalBrightness(v).then(() => updateBrightness()),
applyInternalBrightness(v),
setDarkModeBasedOnBrightness(v),
]),
);
}),
)
.subscribe();
let displays: Display[] = [];
function sleep(ms: number): Promise<void> {
return new Promise(resolve => {
setTimeout(() => resolve(), ms);
});
}
示例7: getBufferPaddings
/**
* Build up buffer for a single Representation.
*
* Download and push segments linked to the given Representation according
* to what is already in the SourceBuffer and where the playback currently is.
*
* Multiple RepresentationBuffer observables can run on the same SourceBuffer.
* This allows for example smooth transitions between multiple periods.
*
* @param {Object} args
* @returns {Observable}
*/
export default function RepresentationBuffer<T>({
clock$, // emit current playback informations
content, // all informations about the content we want to play
queuedSourceBuffer, // allows to interact with the SourceBuffer
segmentBookkeeper, // keep track of what segments already are in the SourceBuffer
segmentFetcher, // allows to download new segments
terminate$, // signal the RepresentationBuffer that it should terminate
wantedBufferAhead$, // emit the buffer goal
} : IRepresentationBufferArguments<T>) : Observable<IRepresentationBufferEvent<T>> {
const { manifest, period, adaptation, representation } = content;
const codec = representation.getMimeTypeString();
const bufferType = adaptation.type;
const initSegment = representation.index.getInitSegment();
// Compute paddings, then used to calculate the wanted range of Segments
// wanted.
const paddings = getBufferPaddings(adaptation);
// Saved initSegment state for this representation.
let initSegmentObject : ISegmentObject<T>|null = initSegment == null ?
{ segmentData: null, segmentInfos: null, segmentOffset: 0 } : null;
// Subject to start/restart a Buffer Queue.
const startQueue$ = new ReplaySubject<void>(1);
// Segments queued for download in the BufferQueue.
let downloadQueue : IQueuedSegment[] = [];
// Emit when the current queue of download is finished
const finishedDownloadQueue$ = new Subject<void>();
// Keep track of the informations about the pending Segment request.
// null if no request is pending.
let currentSegmentRequest : ISegmentRequestObject<T>|null = null;
// Keep track of downloaded segments currently awaiting to be appended to the
// SourceBuffer.
const sourceBufferWaitingQueue = new SimpleSet();
const status$ = observableCombineLatest(
clock$,
wantedBufferAhead$,
terminate$.pipe(take(1), mapTo(true), startWith(false)),
finishedDownloadQueue$.pipe(startWith(undefined))
).pipe(
map(function getCurrentStatus([timing, bufferGoal, terminate]) : {
discontinuity : number;
isFull : boolean;
terminate : boolean;
neededSegments : IQueuedSegment[];
shouldRefreshManifest : boolean;
} {
const buffered = queuedSourceBuffer.getBuffered();
segmentBookkeeper.synchronizeBuffered(buffered);
const neededRange =
getWantedRange(period, buffered, timing, bufferGoal, paddings);
const discontinuity = !timing.stalled || !manifest.isLive ?
-1 : representation.index.checkDiscontinuity(timing.currentTime);
const shouldRefreshManifest = representation.index
.shouldRefresh(neededRange.start, neededRange.end);
let neededSegments = getSegmentsNeeded(representation, neededRange)
.filter((segment) => shouldDownloadSegment(segment, neededRange))
.map((segment) => ({
priority: getSegmentPriority(segment, timing),
segment,
}));
if (initSegment != null && initSegmentObject == null) {
neededSegments = [ // prepend initialization segment
{
segment: initSegment,
priority: getSegmentPriority(initSegment, timing),
},
...neededSegments,
];
}
const isFull = !neededSegments.length && period.end != null &&
neededRange.end >= period.end;
return {
discontinuity,
isFull,
terminate,
neededSegments,
shouldRefreshManifest,
//.........这里部分代码省略.........