rxjs.订阅方法中包含代码是一种好习惯吗? [英] rxjs. is it good practice to have code in subscribe method?

查看:67
本文介绍了rxjs.订阅方法中包含代码是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得很久以前我找到了一个建议,避免使用subscribe方法中的任何代码,而改用管道.

I remember once upon a time I found a recommendation to avoid any code in subscribe method and use pipes instead.

// suppose bad
observable.subscribe(() => dosmg())

// suppose good
observable
    .pipe(tap(() => dosmg()))
    .subscribe()

推理与摇树有关.第二个选项提示更好地被优化.如今,我再也找不到该建议和相反的建议了.我遇到的许多学习资料都在subscribe方法中添加了代码,而没有进行解释.是否仍然建议使用管道代替subscribe中的代码?

The reasoning was related to tree shaking. The second option prompted to be better optimizable. Nowadays I can not find this recommendation anymore as well as the opposite recommendation. And lots of learning materials I encountered are adding the code in the subscribe method without explanations. Is it still recommended to use pipes instead of the code in subscribe?

推荐答案

我通常避免在订阅中添加逻辑.

I normally avoid putting logics in subscribe.

函数式编码的美在于您可以结合,压缩,合并和扩展您的观测值.

The beauty of functional coding is you can combine, zip, merge and extend your observables.

如果您将逻辑放在订阅中,则只是失去了可移植性,并且在以后的阶段更难重构.这是典型的流切片组合方案

If you put logics in subscribe it just simply lose the portability and harder to refactor at the later stage. Here is a typical stream slicing combining scenario

const stream1=observable
    .pipe(tap(() => dosmg()))

const stream1WithLoggin=stream1.pipe(tap(message=>console.log(message))
const stream1WithHttp=stream1.pipe(mergeMap(message=>fetch(someurl))

这篇关于rxjs.订阅方法中包含代码是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆