rxjs observable reusing logic

折月煮酒 提交于 2020-08-24 09:51:58

问题


I'm writing a angular file-upload component.

Upon successful upload, it displays a notice and two buttons:

  • replace : deletes uploaded file and opens the file-selector dialog
  • remove : deletes uploaded file and displays a notice

Deleting the uploaded file means making a HTTP DELETE request to a backend system and handling possible failure and retries.

_handleReplace() {
  this.replaceClicked$.pipe(
    tap((x) => this._backend.delete(this.file, this.fieldName)),
    tap((x) => openFileSelectorDialog())
  );
}

_handleRemove() {
  this.replaceClicked$.pipe(
    tap((x) => this._backend.delete(this.file, this.fieldName)),
    tap((x) => displayNotice())
  );
}

In this snippet I'm not dealing with possible failure and retries.

How can I extract the deletion logic to avoid repeating it in two methods?

Or more generically, how can I apply common transformations on two different observables?

Thank you!


回答1:


You can use the pipe method to create a custom operator like this:

deleteFile = () => pipe(
    tap((x) => this._backend.delete(this.file, this.fieldName))
  );    

_handleReplace() {
  this.replaceClicked$.pipe(
    deleteFile(),
    tap((x) => openFileSelectorDialog())
  );
}

_handleRemove() {
  this.replaceClicked$.pipe(
    deleteFile(),
    tap((x) => displayNotice())
  );
}

The pipe function should be imported from rxjs:

import { pipe } from "rxjs";


来源:https://stackoverflow.com/questions/50907458/rxjs-observable-reusing-logic

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