本文整理汇总了TypeScript中apollo-link.Observable.subscribe方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Observable.subscribe方法的具体用法?TypeScript Observable.subscribe怎么用?TypeScript Observable.subscribe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类apollo-link.Observable
的用法示例。
在下文中一共展示了Observable.subscribe方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: resolve
return new Promise<R>((resolve, reject) => {
observable.subscribe({
next: data => {
if (completed) {
console.warn(
`Promise Wrapper does not support multiple results from Observable`,
);
} else {
completed = true;
resolve(data);
}
},
error: reject,
});
});
示例2: Promise
export function observableToAsyncIterable<T>(observable: Observable<T>): AsyncIterator<T> {
const pullQueue: Callback[] = [];
const pushQueue: any[] = [];
let listening = true;
const pushValue = ({ data }: any) => {
if (pullQueue.length !== 0) {
pullQueue.shift()({ value: data, done: false });
} else {
pushQueue.push({ value: data });
}
};
const pushError = (error: any) => {
if (pullQueue.length !== 0) {
pullQueue.shift()({ value: { errors: [error] }, done: false });
} else {
pushQueue.push({ value: { errors: [error] } });
}
};
const pullValue = () => {
return new Promise(resolve => {
if (pushQueue.length !== 0) {
const element = pushQueue.shift();
// either {value: {errors: [...]}} or {value: ...}
resolve({
...element,
done: false,
});
} else {
pullQueue.push(resolve);
}
});
};
const subscription = observable.subscribe({
next(value: any) {
pushValue(value);
},
error(err: Error) {
pushError(err);
},
});
const emptyQueue = () => {
if (listening) {
listening = false;
subscription.unsubscribe();
pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));
pullQueue.length = 0;
pushQueue.length = 0;
}
};
return {
async next() {
return listening ? pullValue() : this.return();
},
return() {
emptyQueue();
return Promise.resolve({ value: undefined, done: true });
},
throw(error) {
emptyQueue();
return Promise.reject(error);
},
[$$asyncIterator]() {
return this;
},
};
}