我想知道如何使用await / async和RxJS在typescript中做类似的事情:
async function bar(): Promise<boolean>{ ... }
function boo(): Observable<any> { ... }
function baz(): Observable<any> {
return Observable
.fromPromise(() => bar())
.map(() => boo())
}
总结一下,我有多个baz流,我将稍后用 zip 链接。在每个baz()中,我需要做一些异步检查。 但没有任何附加...... Observable.fromPromise正在按预期工作。嘘不。这就像我订阅流( zip(baz1(),baz2()))时,boo永远不会被执行。
我错过了什么吗?这个故事中最好的做法是什么?
编辑:
以下是代码的第一部分:
syncResource(urlEndpoint: string, storeCollectionKey: string): Observable<any> {
return Observable
.fromPromise(this.shouldSyncResource(urlEndpoint, storeCollectionKey))
.map((shouldUpdateResource) => {
if(!shouldUpdateResource){ return Observable.empty(); }
// here i can get "shouldUpdateResource" value
return this._Remote.get(urlEndpoint, this._getRequestOptions())
.map((response: Response) => response.json())
.map((collection) => {
collection.forEach((item) => {
this._Stores[storeCollectionKey].update(item);
});
});
});
}
以下是第二部分:
Observable.zip(
syncResource('/poultries', 'poultriesStoreKey'),
syncResource('/buildings', 'buildingsStoreKey')
).subscribe(() => console.log('Syncing done'))
答案 0 :(得分:0)
好的,它已经解决了。我需要在代码的第二部分使用 mergeMap 和返回值:
syncResource(urlEndpoint: string, storeCollectionKey: string): Observable<any> {
return Observable
.fromPromise(this.shouldSyncResource(urlEndpoint, storeCollectionKey))
.mergeMap((shouldUpdateResource, index) => {
if(!shouldUpdateResource){ return Observable.empty(); }
return this._Remote.get(urlEndpoint, this._getRequestOptions())
.do((response: Response) => this.rememberResponseHashIfPresent(response.headers.get('x-hash'), storeCollectionKey))
.map((response: Response) => {
console.log(response.json());
return response.json();
})
.map((collection) => {
collection.forEach((item) => this._Stores[storeCollectionKey].update(item));
return true;
});
});
}