哪个rxjs运算符在映射后进行额外的转换? [英] Which rxjs operator to make extra transformation after mapping?
问题描述
this.service.retrieveObject(id).map((object)=>{ return transformation1(object); })
.map((object)=>{ return transformation2(object); });
在示例中,在 transformation1
被释放后,第二个 map
调用无法访问对象.
In the exemple bellow the second map
call doesn't have access to object after transformation1
exexuted.
我需要使用哪个运算符进行嵌套转换(transformation2优于transformation1)?
Which operator do I need to use to make nested transformations (transformation2 over transformation1)?
推荐答案
map
是进行转换的正确运算符. map
本质上是 a->b
函数,您可以在其中输入 a
并输出 b
.随后对 map
的调用将获取输出对象.
map
is the correct operator to make transformations. map
is essentially an a -> b
function where you input an a
and output a b
. Any subsequent calls to map
would get the output object.
两次调用 map
的缺点是,您实际上在对象上进行了两次迭代.虽然在小对象上虽然没什么大不了,但是列表很大,性能会下降.您可以将 transformation1
和 transformation2
函数有效地组合为一个函数,并且仅调用一次 map
.或者让 transformation2
从 transformation1
获取返回对象.将这两种操作合并到一个调用中会更有效.
The downside the calling map
twice is that you are effectively iterating over the object twice. While on small objects that might not be a big deal, but take a large list and performance will decrease. You can effectively combine your transformation1
and transformation2
functions into a single function and only call map
once. Or make transformation2
take the return object from transformation1
. It would be more efficient to combine both operations into a single call.
this.service.retrieveObject(id)
.map(object => transformation2(transformation1(object)));
更新1/17/2018
如果Transformation1和Transformation2是异步的,那么使用 switchMap
怎么办? switchMap
从第一个可观察对象获取结果,并将其传递给第二个可观察对象.
If transformation1 and transformation2 are asynchronous, what about using switchMap
? switchMap
takes the result from the first observable and passes it to the second observable.
this.service.retrieveObject(id)
.switchMap(retrieveObjectResponse => transformation1(retrieveObjectResponse))
.switchMap(transformation1Response => transformation2(transformation1Response));
这篇关于哪个rxjs运算符在映射后进行额外的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!