Manage the flow of page events using RXJS

In the background system, as well as in the data system, an area often contains multiple input boxes, buttons and other operations, respectively control the different functions in the page. Often we initiate requests in a callback to a registered event, which causes the following problems:

1. The event callback function has a lot of responsibilities. Sometimes, it needs to link with other conditions to trigger data update and deal with its own data problems in the callback.

2. The event management is not clear. When multiple conditions change at the same time and linkage exists, it is too complicated to handle, resulting in poor scalability.

3. HTTP request efficiency is the same as HTTP request efficiency.

We can think of the variable value of each input as a stream, implemented in the code by Subject, and streams with repeated functions can be aggregated into the same stream for later use.

The code implementation is as follows:

@Component({
  selector: 'app-event-stream'.template:  
      
< / div > < div > < label > label: 4

table1Data: {{table1Data}}

table2Data: {{table2Data}}

table3Data: {{table3Data}}

table4Data: {{table4Data}}

`
.styleUrls: ['./event-stream.component.scss']})export class EventStreamComponent implements OnInit { // Input event streams for each page input1$ = new BehaviorSubject(' '); input2$ = new BehaviorSubject(' '); input3$ = new BehaviorSubject(' '); input4$ = new BehaviorSubject(' '); // Enter values for each page str1 = ' '; str2 = ' '; str3 = ' '; str4 = ' '; // Display corresponding page data respectivelytable1Data? ; table2Data? ; table3Data? ; table4Data? ; table4$: Observable<string>; table3$: Observable<string>; table2$: Observable<string>; table1$: Observable<string>; getTableData(strs: string[]) { return of(strs.reduce((accumulator, currentValue) = > accumulator + '+' + currentValue)); } constructor(){}private pipeCommonInput<T>(ob: Observable<T>): Observable<T> { return ob.pipe( debounceTime(300), distinctUntilChanged(), ); } ngOnInit(): void { // Table4 data subscription this.table4$ = this.pipeCommonInput(this.input4$); this.table3$ = this.pipeCommonInput(merge(this.input4$, this.input3$)); this.table2$ = this.pipeCommonInput(merge(this.input4$, this.input3$, this.input2$)); this.table1$ = this.pipeCommonInput(merge(this.input4$, this.input3$, this.input2$, this.input1$)); this.table4$ .pipe(switchMap(() = > this.getTableData([this.str4]))) .subscribe(res= > { this.table4Data = res; }); this.table3$ .pipe(switchMap(() = > this.getTableData([this.str4, this.str3]))) .subscribe(res= > { this.table3Data = res; }); this.table2$ .pipe(switchMap(() = > this.getTableData([this.str4, this.str3, this.str2]))) .subscribe(res= > { this.table2Data = res; }); this.table1$ .pipe(switchMap(() = > this.getTableData([this.str4, this.str3, this.str2, this.str1]))) .subscribe(res= > { this.table1Data = res; }); }}Copy the code