Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing code in Angular 2, RxJS -- repetitive code within Subscriber body

Problem

I'm using a couple of BehaviourSubject vars in Angular2 to get data from a service and update an Array in the controller.

The problem is all the respective .subscribe() functions carry out the same operations and I cannot find a way to reuse the code -- maybe passing a lambda function into the body of the .subscribe()?

It doesn't make sense to retype the same code again and again -- it impacts the readability of the component.

Scenario:

Updating a chart with data from different sources

this.catagoryASubject.subscribe(
        value => {
            // updating array and chart
            this.radarChartData.forEach((val, i) => { if (val.label == value.name) { this.radarChartData[i].data = value.data } });
        },
        err => console.log("error"),
        () => console.log("complete")
    );

this.catagoryBSubject.subscribe(
        // same code as in the above subscriber
    );
like image 611
Dhruvan Ganesh Avatar asked Apr 29 '26 07:04

Dhruvan Ganesh


1 Answers

You can use let() operator to group common functionality of observable chains. It takes observable as input and returns an observable, so you could write:

function updateChart(observable: Observable<any>) {
  return observable
    .map(value => {/* do your thing*/})
 // .filter().switchMap().do() // whatever
    .catch(error => console.log("error"))
}

and then use it:

this.catagoryASubject.let(updateChart).subscribe();
this.catagoryBSubject.let(updateChart).subscribe();
this.catagoryCSubject.let(updateChart).subscribe();

I prefer to use subscribe() just as a trigger, and not do any processing work there. It's much cleaner, and you can easily switch to async pipe when you need to...

this.A = this.catagoryASubject.let(updateChart);

<div> {{ A |async |json }} </div>
like image 72
Sasxa Avatar answered Apr 30 '26 21:04

Sasxa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!