RxJS 中的管道是什么? [英] What is pipe for in RxJS?
问题描述
我想我有基本的概念,但还有一些晦涩之处
所以总的来说,这就是我使用 Observable
的方式:
observable.subscribe(x => {})
如果我想过滤数据,我可以使用这个:
import { first, last, map, reduce, find, skipWhile } from 'rxjs/operators';observable.pipe(地图(x => {返回x}),第一的()).订阅(x => {})
我也可以这样做:
import 'rxjs/add/operator/map';导入 'rxjs/add/operator/first';observable.map(x => {return x}).first().subscribe(x => {})
所以我的问题是:
- 有什么区别?
- 如果没有区别,为什么函数
pipe
存在? - 为什么这些函数需要不同的导入?
pipeable"(以前的可出租")运算符是自 RxJS 5.5 以来当前和推荐的使用运算符的方式.
我强烈建议您阅读有关可管道操作符的官方文档>
主要区别在于,创建自定义操作符更容易,并且在不改变某些全局 Observable
对象的情况下,如果两个不同的方想要创建相同的操作符,可能会发生冲突名字.
为每个运算符 'rxjs/add/operator/first'
使用单独的 import
语句是制作更小的应用程序包的一种方式.通过仅导入您需要的操作符而不是整个 RxJS 库,您可以显着减少总包大小.但是,编译器无法知道您是否导入了 'rxjs/add/operator/first'
因为您在代码中确实需要它,或者您在重构代码时忘记删除它.这是使用可管道操作符的优势之一,其中未使用的导入会被自动忽略.
I think I have the base concept, but there are some obscurities
So in general this is how I use an Observable
:
observable.subscribe(x => {
})
If I want to filter data I can use this:
import { first, last, map, reduce, find, skipWhile } from 'rxjs/operators';
observable.pipe(
map(x => {return x}),
first()
).subscribe(x => {
})
I can also do this:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
observable.map(x => {return x}).first().subscribe(x => {
})
So my questions are:
- What is the difference?
- If there is no difference, why the function
pipe
exists? - Why those functions need different imports?
The "pipeable" (former "lettable") operators is the current and recommended way of using operators since RxJS 5.5.
I strongly recommend you to read the official documentation on pipeable operators
The main difference is that it's easier to make custom operators and that it's better treeshakable while not altering some global Observable
object that could possible make collisions if two different parties wanted to create an operator of the same name.
Using separate import
statement for each operator 'rxjs/add/operator/first'
was a way to make smaller app bundles. By importing only operators you need instead of the entire RxJS library you can significantly reduce the total bundle size. However the compiler can't know if you imported 'rxjs/add/operator/first'
because you really need it in you code or you just forgot to remove it when refactoring your code. That's one of the advantages of using pipeable operators where unused imports are ignored automatically.
这篇关于RxJS 中的管道是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!