Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs observable reusing logic

Tags:

angular

rxjs

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!

like image 304
Cec Avatar asked Jun 18 '18 10:06

Cec


1 Answers

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";
like image 200
Mohamed Gara Avatar answered Oct 12 '22 09:10

Mohamed Gara