本文整理汇总了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();
});