rxjs. is it good practice to have code in subscribe method?

孤人 提交于 2019-12-08 11:56:04

问题


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()

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?


回答1:


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))


来源:https://stackoverflow.com/questions/55001680/rxjs-is-it-good-practice-to-have-code-in-subscribe-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!