我正在使用 RxJS 和 redux-observable。
我正在尝试读取史诗中的文件。在我的情况下,我必须在史诗中做到这一点,因为其他一些史诗由expand
操作员触发了这个史诗多次“未知” 。
但由于 FileReader 是异步的,下面的代码不起作用。
处理这个问题的正确方法是什么,尤其是 RxJS 方法?谢谢
export const uploadAttachmentEpic = (action$, store) =>
action$
.ofType(UPLOAD_ATTACHMENT)
.map(action => {
const reader = new FileReader();
reader.onload = () => {
return {
...action,
payload: {
...action.payload,
base64: reader.result
}
}
};
reader.readAsDataURL(action.payload.file);
})
.mergeMap(action =>
ajax
.post( /* use action.payload.base64 */ )
.map(uploadAttachmentSucceed)
.catch(uploadAttachmentFailed)
);
范的回答(在撰写本文时)很好,但有一些重要的警告:
它立即开始读取文件而不是懒惰地读取文件。因此readFile(file)
,即使在任何人订阅之前,只需调用即可启动它。这很容易出错,因为有人可能不会立即同步订阅它,然后reader.onload
就会错过它。理想情况下,可观察对象是完全惰性且可重复的工厂。
它从不调用obs.complete()
观察者,因此订阅可能会导致内存泄漏,因为它永远不会结束。
观察者上的方法不受约束,因此reader.onerror = obs.error
实际上不会起作用。相反,您需要e => obs.error(e)
或obs.error.bind(obs)
查看此处以了解原因
它不会在取消订阅时中止阅读。
这是我将如何做到的:
function readFile(file){
// Could use Observable.create (same thing) but I
// prefer this one because Observable.create is
// not part of the TC39 proposal
return new Observable(observer => {
const reader = new FileReader();
reader.onload = (e) => {
observer.next(reader.result);
// It's important to complete() otherwise this
// subscription might get leaked because it
// "never ends"
observer.complete();
};
reader.onerror = e => observer.error(e);
reader.readAsDataURL(file);
// unsubscribe handler aka cleanup
return () => {
// LOADING state.
// Calling abort() any other time
// will throw an exception.
if (reader.readyState === 1) {
reader.abort();
}
};
});
}
这种模式几乎可以应用于任何 API,因此了解它的工作原理非常方便。
我希望范不介意批评!我没有冒犯的意思,只是想分享知识。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句