user2080105
user2080105

Reputation: 1686

Which rxjs operator to make extra transformation after mapping?

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

Upvotes: 1

Views: 125

Answers (2)

Tyler Jennings
Tyler Jennings

Reputation: 8911

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

Upvotes: 1

user4676340
user4676340

Reputation:

Try this one !

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

Upvotes: 0

Related Questions