使用具有语义意义并减少混乱的函数重构Rxjs可观察对象

时间:2018-07-25 15:57:17

标签: angular rxjs refactoring

我想重构一连串可观察的东西,以便让它们产生语义感觉,我的代码看起来与此接近。

//Ajax call that gets the users data
this.getUser
  .pipe(
    flatmap((user)=>{
       //Stuff that gets the user's picture
    }),
    flatmap((picture)=>{
       //Stuff that saves the user's picture
    }),
  )

所有这些都不具有语义意义,我需要阅读代码以了解它的作用,我想对其进行重构以使其看起来像这样。

this.getUser
  .pipe(
    getPicture(),
    savePicture()
  )

function getPicture(user){
  //Stuff that gets the user's picture
  return picture
}


function savePicture(picture){
  //Stuff that saves the user's picture
}

如何重构原始代码,使其结构更简洁,可读性更好?

1 个答案:

答案 0 :(得分:0)

this.getUser.pipe(getPicture, savePicture);

export function getPicture(user$: Observable<user>) =>
    (user$) => user$.pipe(flatmap((user) => {
        //Stuff that gets the user's picture
    });


export function savePicture(picture$: Observable<Picture>) =>
    (picture$) => picture$.pipe(flatmap((picture) => {
        //Stuff that saves the user's picture
    });