本文整理匯總了TypeScript中rxjs/operators.finalize函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript finalize函數的具體用法?TypeScript finalize怎麽用?TypeScript finalize使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了finalize函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: it
it('should call two finalize instances in succession on a shared Observable', (done: MochaDone) => {
let invoked = 0;
function checkFinally() {
invoked += 1;
if (invoked === 2) {
done();
}
}
of(1, 2, 3).pipe(
finalize(checkFinally),
finalize(checkFinally),
share()
).subscribe();
});
示例2: it
it("should emit once if source open several times", (done) => {
const fakeMediaSource = {
readyState: "closed",
};
const mockOnSourceOpen$ = jest.fn(() => {
return observableInterval(500).pipe(
tap(() => fakeMediaSource.readyState = "open"),
mapTo(null)
);
});
jest.mock("../event_listeners", () => ({
__esModule: true,
onSourceOpen$: mockOnSourceOpen$,
}));
const whenMediaSourceOpen$ = require("../when_media_source_open").default;
whenMediaSourceOpen$(fakeMediaSource).pipe(
finalize(() => {
expect(fakeMediaSource.readyState).toBe("open");
expect(mockOnSourceOpen$).toHaveBeenCalledTimes(1);
done();
})
)
.subscribe();
});
示例3: waitUntilWatchIsReady
export function waitUntilWatchIsReady(
stream: NodeJS.EventEmitter,
opts: IWatchOptions = {}
) {
const buildOutput$ = new Rx.Subject<string>();
const onDataListener = (data: Buffer) =>
buildOutput$.next(data.toString('utf-8'));
const onEndListener = () => buildOutput$.complete();
const onErrorListener = (e: Error) => buildOutput$.error(e);
stream.once('end', onEndListener);
stream.once('error', onErrorListener);
stream.on('data', onDataListener);
return Rx.race(getWatchHandlers(buildOutput$, opts))
.pipe(
mergeMap(whenReady => whenReady),
finalize(() => {
stream.removeListener('data', onDataListener);
stream.removeListener('end', onEndListener);
stream.removeListener('error', onErrorListener);
buildOutput$.complete();
})
)
.toPromise();
}
示例4: it
it('should pass current index to accumulator', () => {
const values = {
a: 1, b: 3, c: 5,
x: 1, y: 4, z: 9
};
let idx = [0, 1, 2];
const e1 = hot('--a--b--c--|', values);
const e1subs = '^ !';
const expected = '--x--y--z--|';
const scanFunction = (o: number, value: number, index: number) => {
expect(index).to.equal(idx.shift());
return o + value;
};
const scanObs = e1.pipe(
scan(scanFunction, 0),
finalize(() => {
expect(idx).to.be.empty;
})
);
expectObservable(scanObs).toBe(expected, values);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
示例5: getHeroes
getHeroes() {
this.heroes = [];
this.http.get(heroesUrl).pipe(
catchError(this.catchBadResponse),
finalize(() => this.hideSpinner())
).subscribe((heroes: Hero[]) => this.heroes = heroes);
}
示例6: saveSet
private saveSet(done: () => void = () => { }) {
this.isSaving = true;
const workout = this.workout;
const workoutLog = this.state.getCurrentWorkoutLog();
const indices = this.state.getCurrentTraversalIndices();
return this.workoutsControllerProxy.saveWorkoutLog(workout.workoutId, workoutLog)
.pipe(
finalize(
() => {
this.isSaving = false;
}),
this.takeUntilUnsubscribed())
.subscribe(
response => {
this.workout.workoutDetails[indices.detailIndex].workoutLogs[indices.setIndex] = response.body;
this.workoutsControllerProxy.updateCachedWorkout(this.workout);
done();
return response;
},
errorResponse => {
this.errorMessage = errorResponse.statusText;
return errorResponse;
}
);
}
示例7: startUpload
startUpload(event: FileList) {
// The File object
const file = event.item(0);
// Client-side validation example
if (file.type.split('/')[0] !== 'image') {
console.error('unsupported file type :( ');
return;
}
// The storage path
const path = `test/${new Date().getTime()}_${file.name}`;
// Totally optional metadata
const customMetadata = { app: 'My AngularFire-powered PWA!' };
// The main task
this.task = this.storage.upload(path, file, { customMetadata });
// Progress monitoring
this.percentage = this.task.percentageChanges();
this.snapshot = this.task.snapshotChanges().pipe(
tap(snap => {
if (snap.bytesTransferred === snap.totalBytes) {
// Update firestore on completion
this.db.collection('photos').add({ path, size: snap.totalBytes });
}
}),
finalize(() => this.downloadURL = this.storage.ref(path).getDownloadURL() )
);
// The file's download URL
}
示例8: getWords
private getWords(titles: string[], locale: Locale, source: SearchResultsSource, progressObserver?: Observer<number>) {
let progress = 0;
let rateLimitingDelay = 0;
const getWords = titles.map(title => {
const getWord = of(null).pipe(
delay(rateLimitingDelay), // Adding delay for rate limiting to prevent HTTP error 429 from backend.
mergeMap(_ => this.getWordByLoadingSearchResults(title, locale, source)),
finalize(() => {
if (progressObserver) {
progress++;
progressObserver.next(progress);
}
})
);
rateLimitingDelay += 1000;
return getWord;
});
return zip(...getWords).pipe(
finalize(() => {
if (progressObserver) {
progressObserver.complete();
}
})
);
}
示例9: intercept
intercept(req: HttpRequest<any>, next: HttpHandler) {
const started = Date.now();
let ok: string;
// extend server response observable with logging
return next.handle(req)
.pipe(
tap(
// Succeeds when there is a response; ignore other events
event => ok = event instanceof HttpResponse ? 'succeeded' : '',
// Operation failed; error is an HttpErrorResponse
error => ok = 'failed'
),
// Log when response observable either completes or errors
finalize(() => {
const elapsed = Date.now() - started;
const msg = `${req.method} "${req.urlWithParams}" ${ok} in ${elapsed} ms.`;
if(ok == "failed"){
this.logger.error(msg);
}else{
this.logger.trace(msg);
}
})
);
}
示例10: interval
'from a shared Observable', (done: MochaDone) => {
interval(50).pipe(
finalize(done),
share()
).subscribe()
.unsubscribe();
});