本文介绍了如何创建 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.
这篇关于如何创建 RxJS Observable 使其在回调函数完成时返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!