问题
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