简体   繁体   English

如何将同步函数调用转换为可观察的?

[英]How to convert synchronous function invocation to an observable?

Is there a standard way or creater in RxJS 6 lib which would convert a function invocation into an observable like this ? RxJS 6 lib中是否存在将函数调用转换为可观察的标准方法或创建器

const liftFun = fun => {
    try {
        return of(fun())
    } catch (err) {
        return throwError(err)
    }
}

To observable 为了可观察

 const liftFun=fun=>new Observable(obs=>{
        try {
            return obs.next(fun)
        } catch (err) {
            return obs.error(err)
        }
    })

Or you want to convert to operator function to be used in pipe chain 或者您想要转换为要在pipe链中使用的运算符函数

const liftFun = fun => mergeMap(fun=>({
    try {
        return of(fun())
    } catch (err) {
        return throwError(err)
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM