Home > Software design >  How to optimize RXJS operator to avoid messy code?
How to optimize RXJS operator to avoid messy code?

Time:07-13

I try to avoid messy code using RXjs. There is a following code:

combineLatest([
  this.usersService.userRightsObs$,
  this.layersService.flatLayersObs$,
])
.pipe(debounceTime(300))
.subscribe(([userRights, treeLayers]) => {
  const editableLayers = userRights.editableLayers.map((layerId) => {
    return treeLayers.get(layerId.toString());
  });
  this.layersService.setEditableLayers(editableLayers);
});

So, I dislike that my code look messy in this place:

const editableLayers = userRights.editableLayers.map((layerId) => {
  return treeLayers.get(layerId.toString());
});
    
this.layersService.setEditableLayers(editableLayers);

I think it is not responsible place.

CodePudding user response:

welcome to the StackOverflow. In your case, there's not much to upgrade, really. You can move mapping to the operator and use anonymous functions to shorten the code though.

combineLatest([
  this.usersService.userRightsObs$,
  this.layersService.flatLayersObs$,
])
.pipe(
  debounceTime(300)
  map(([userRights, treeLayers]) => userRights.editableLayers.map((layerId) => treeLayers.get(layerId.toString()))
)
.subscribe(editableLayers => {
  this.layersService.setEditableLayers(editableLayers);
});

CodePudding user response:

Like @mat.hudak said, I wouldn't say there's much to improve optically. You could, if you wish, use tap operator to trigger the side-effect and leave the subscribe() empty.

combineLatest([
  this.usersService.userRightsObs$,
  this.layersService.flatLayersObs$,
])
.pipe(
  debounceTime(300),
  tap(([userRights, treeLayers]) => 
    this.layersService.setEditableLayers(
      userRights.editableLayers.map((layerId) =>
        treeLayers.get(layerId.toString())
      )
    )
  )
)
.subscribe();

Note that single line arrow functions with enclosing curly braces return statement and without enclosing curly braces and return statement are equivalent.

userRights.editableLayers.map((layerId) => {
  return treeLayers.get(layerId.toString());
})

is equivalent to

userRights.editableLayers.map((layerId) =>
  treeLayers.get(layerId.toString())
)
  • Related