本文整理汇总了TypeScript中rxjs/Subject.Subject.switchMap方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Subject.switchMap方法的具体用法?TypeScript Subject.switchMap怎么用?TypeScript Subject.switchMap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rxjs/Subject.Subject
的用法示例。
在下文中一共展示了Subject.switchMap方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: errorHandler
export function createSubject<T>(
successHandler: StreamSuccessHandler<T>,
errorHandler: StreamErrorHandler
): ISubject<Promise<T>> {
const subject = new Subject<Promise<T>>();
const subscription = subject
// This ensures we get last added promise
.switchMap<Promise<T>, T>(identity)
// Streams are closed on error by default so we need this workaround
.catch((error, caught) => {
errorHandler(error); // handle error
return caught; // stream continue
})
.subscribe(successHandler);
const wrapper: ISubject<Promise<T>> = {
next: (promise: Promise<T>) => {
subject.next(promise);
},
unsubscribe: () => {
subscription.unsubscribe();
subject.unsubscribe();
}
};
return wrapper;
}
示例2: it
it('should work', () => {
const getUserData = userId => Observable.of(`data for user ${userId}`);
const userIdSubject = new Subject<string>();
const log: string[] = [];
userIdSubject.switchMap(userId => getUserData(userId))
.subscribe(userData => log.push(`user data: ${userData}`));
userIdSubject.next('123');
expect(log).toEqual(['user data: data for user 123']);
userIdSubject.next('222');
expect(log).toEqual(['user data: data for user 123', 'user data: data for user 222']);
});
示例3: StoreService
function StoreService(): D1StoreServiceType {
'ngInject';
let _stores: D1Store[] = [];
// A subject that keeps track of the current account. Because it's a
// behavior subject, any new subscriber will always see its last
// value.
const accountStream = new BehaviorSubject<DestinyAccount | null>(null);
// The triggering observable for force-reloading stores.
const forceReloadTrigger = new Subject();
// A stream of stores that switches on account changes and supports reloading.
// This is a ConnectableObservable that must be connected to start.
const storesStream = accountStream
// Only emit when the account changes
.distinctUntilChanged(compareAccounts)
// But also re-emit the current value of the account stream
// whenever the force reload triggers
.merge(forceReloadTrigger.switchMap(() => accountStream.take(1)))
// Whenever either trigger happens, load stores
.switchMap(loadingTracker.trackPromise(loadStores))
// Keep track of the last value for new subscribers
.publishReplay(1);
// TODO: If we can make the store structures immutable, we could use
// distinctUntilChanged to avoid emitting store updates when
// nothing changed!
const service = {
getActiveStore: () => _stores.find((s) => s.current),
getStores: () => _stores,
getStore: (id) => _stores.find((s) => s.id === id),
getVault: () => _stores.find((s) => s.isVault) as D1Vault | undefined,
getAllItems: () => _.flatMap(_stores, (s) => s.items),
refreshRatingsData() {
return;
},
getStoresStream,
getItemAcrossStores,
updateCharacters,
reloadStores,
touch() {
store.dispatch(update({ stores: _stores }));
}
};
return service;
/**
* Find an item among all stores that matches the params provided.
*/
function getItemAcrossStores(params: {
id?: string;
hash?: number;
notransfer?: boolean;
amount?: number;
}) {
const predicate = _.iteratee(_.pick(params, 'id', 'hash', 'notransfer', 'amount')) as (
i: DimItem
) => boolean;
for (const store of _stores) {
const result = store.items.find(predicate);
if (result) {
return result;
}
}
return undefined;
}
/**
* Update the high level character information for all the stores
* (level, light, int/dis/str, etc.). This does not update the
* items in the stores - to do that, call reloadStores.
*/
function updateCharacters(account: DestinyAccount) {
// TODO: the router.globals.params defaults are just for now, to bridge callsites that don't know platform
if (!account) {
if (router.globals.params.membershipId && router.globals.params.platformType) {
account = {
membershipId: router.globals.params.membershipId,
platformType: router.globals.params.platformType,
displayName: 'Unknown',
platformLabel: 'Unknown',
destinyVersion: 1
};
} else {
throw new Error("Don't know membership ID and platform type");
}
}
return Promise.all([getDefinitions(), getCharacters(account)]).then(([defs, bungieStores]) => {
_stores.forEach((dStore) => {
if (!dStore.isVault) {
const bStore = bungieStores.find((s) => s.id === dStore.id)!;
dStore.updateCharacterInfo(defs, bStore.base);
}
});
service.touch();
//.........这里部分代码省略.........
示例4: makeD2StoresService
/**
* TODO: For now this is a copy of StoreService customized for D2. Over time we should either
* consolidate them, or at least organize them better.
*/
function makeD2StoresService(): D2StoreServiceType {
'ngInject';
let _stores: D2Store[] = [];
// A subject that keeps track of the current account. Because it's a
// behavior subject, any new subscriber will always see its last
// value.
const accountStream = new BehaviorSubject<DestinyAccount | null>(null);
// The triggering observable for force-reloading stores.
const forceReloadTrigger = new Subject();
// A stream of stores that switches on account changes and supports reloading.
// This is a ConnectableObservable that must be connected to start.
const storesStream = accountStream
// Only emit when the account changes
.distinctUntilChanged(compareAccounts)
// But also re-emit the current value of the account stream
// whenever the force reload triggers
.merge(forceReloadTrigger.switchMap(() => accountStream.take(1)))
// Whenever either trigger happens, load stores
.switchMap(loadStores)
// Keep track of the last value for new subscribers
.publishReplay(1);
// TODO: If we can make the store structures immutable, we could use
// distinctUntilChanged to avoid emitting store updates when
// nothing changed!
const service = {
getActiveStore: () => _stores.find((s) => s.current),
getStores: () => _stores,
getStore: (id: string) => _stores.find((s) => s.id === id),
getVault: () => _stores.find((s) => s.isVault) as D2Vault | undefined,
getAllItems: () => flatMap(_stores, (s) => s.items),
getStoresStream,
getItemAcrossStores,
updateCharacters,
reloadStores,
refreshRatingsData,
touch() {
store.dispatch(update(_stores));
}
};
return service;
/**
* Find an item among all stores that matches the params provided.
*/
function getItemAcrossStores(params: {
id?: string;
hash?: number;
notransfer?: boolean;
amount?: number;
}) {
const predicate = _.iteratee(_.pick(params, 'id', 'hash', 'notransfer', 'amount')) as (
i: DimItem
) => boolean;
for (const store of _stores) {
const result = store.items.find(predicate);
if (result) {
return result;
}
}
return undefined;
}
/**
* Update the high level character information for all the stores
* (level, light, int/dis/str, etc.). This does not update the
* items in the stores - to do that, call reloadStores.
*/
function updateCharacters(account: DestinyAccount): IPromise<D2Store[]> {
// TODO: the router.globals.params defaults are just for now, to bridge callsites that don't know platform
if (!account) {
if (router.globals.params.membershipId && router.globals.params.platformType) {
account = {
membershipId: router.globals.params.membershipId,
platformType: router.globals.params.platformType,
displayName: 'Unknown',
platformLabel: 'Unknown',
destinyVersion: 2
};
} else {
throw new Error("Don't know membership ID and platform type");
}
}
return $q
.all([getDefinitions(), getCharacters(account)])
.then(([defs, profileInfo]: [D2ManifestDefinitions, DestinyProfileResponse]) => {
// TODO: create a new store
_stores.forEach((dStore) => {
if (!dStore.isVault) {
//.........这里部分代码省略.........
示例5: Subject
// A subject that keeps track of the current account. Because it's a
// behavior subject, any new subscriber will always see its last
// value.
const accountStream: Subject<DestinyAccount> = new ReplaySubject<DestinyAccount>(1);
// The triggering observable for force-reloading progress.
const forceReloadTrigger = new Subject();
// A stream of progress that switches on account changes and supports reloading.
// This is a ConnectableObservable that must be connected to start.
const progressStream: ConnectableObservable<ProgressProfile> = accountStream
// Only emit when the account changes
.distinctUntilChanged(compareAccounts)
// But also re-emit the current value of the account stream
// whenever the force reload triggers
.merge(forceReloadTrigger.switchMap(() => accountStream.take(1)))
// Whenever either trigger happens, load progress
.switchMap(loadProgress)
.filter(Boolean)
// Keep track of the last value for new subscribers
.publishReplay(1);
/**
* Set the current account, and get a stream of progress updates.
* This will keep returning progress even if something else changes
* the account by also calling "progressStream". This won't force the
* progress to reload unless they haven't been loaded at all.
*
* @return a stream of store updates
*/
export function getProgressStream(account: DestinyAccount) {