Which rxjs operator to make extra transformation after mapping?

寵の児 提交于 2019-12-14 02:36:57

问题


 this.service.retrieveObject(id).map((object)=>{ return transformation1(object); })
                                .map((object)=>{ return transformation2(object); });

In the exemple bellow the second map call doesn't have access to object after transformation1 exexuted.

Which operator do I need to use to make nested transformations (transformation2 over transformation1)?


回答1:


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.

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

UPDATE 1/17/2018

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



回答2:


Try this one !

this.service.retrieveObject(id).map((object)=>{ return transformation1(object); })
                               .flatMap((object)=>{ return transformation2(object); });


来源:https://stackoverflow.com/questions/48283462/which-rxjs-operator-to-make-extra-transformation-after-mapping

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