如何创建 RxJS Observable 使其在回调函数完成时返回一个值
问题描述:
我需要创建一个 RxJS Observable,以便它在回调函数完成时返回一个值.
I need to create an RxJS Observable such that it returns a value when call back function completes.
下面是代码,我试过了.
Below is the code, I have tried.
我想在订阅 loadMarkerImages 函数的调用者中返回要返回的资源"
I want to return 'resources' to be returned in the caller subscribing to loadMarkerImages function
loadMarkerImages(markerNameAndImageUrlMap) {
let loader = new PIXI.loaders.Loader();
for (let markerKey in markerNameAndImageUrlMap) {
let imageUrl = markerNameAndImageUrlMap[markerKey];
loader.add(markerKey, imageUrl);
}
Observable.create()
return defer(() => {
loader.load((loader, resources) => {
return of(resources);
});
})
}
答
请参阅文档 关于如何创建一个 observable:
See the documentation for how to create an observable:
return new Observable(subscriber => {
let loader = new PIXI.loaders.Loader();
for (let markerKey in markerNameAndImageUrlMap) {
let imageUrl = markerNameAndImageUrlMap[markerKey];
loader.add(markerKey, imageUrl);
}
loader.load((loader, resources) => {
subscriber.next(resources);
subscriber.complete();
});
}
不过,如果 loader.load() 调用可能失败,请确保也处理错误情况.否则返回的 observable 永远不会发出,永远不会完成,永远不会出错.
Make sure to also handle the error case if the loader.load() call can fail, though. Otherwise the returned observable will never emit, never complete, and never error.