简体   繁体   中英

How to use mergeWith with Subjects in Angular

Goal: A Combined Filter with 3 Inputs to filter some list

Restrictions:

  • The User should not be forced to complete all available filters to submit
  • The first submit should happen once the user inputs
  • Different Inputs are combined once there is more than one

My Take: I send the input data from the 3 different input components to Subjects in a Service that should act as event emitter between input and the actual combination, to be able to reuse and cherry pick different inputs as needed

export class FilterInputStoreService {
  public selectedTypesHandler = new Subject<string>();
  public selectedPrivacyOptionsHandler = new Subject<boolean>();
  public searchInputHandler = new Subject<boolean>();
  constructor() {}
}

In the filter combination component i try to "listen" to if a subject sends something and combine it with the rest using mergeWith.

this.filterInputStore.selectedTypesHandler
    .mergeWith(this.filterInputStore.searchInputHandler, this.filterInputStore.selectedCurrenciesHandler )
    .map(() => {
       this.combinedDataObject = {
       Here i combine the values, doesnt matter for the question
        };
         }),
        tap(() => {
          this.filterService.newFilterData(this.combinedDataObject);
        })
       )
        .subscribe();

Problem:

  • It Says mergeWith cannot be used with Subjects
  • Other operators like combineLatest dont work because they require to wait until every of the sources has an input.
  • Cant use Behaviorsubject because that emits an initial value which is null, causing the filter to crash

mergeWith , like merge works seamlessly with Subjects.

Example :

import { Subject } from 'rxjs';
import { mergeWith } from 'rxjs/operators';

const s1 = new Subject<string>();
const s2 = new Subject<string>();
const s3 = new Subject<string>();

s1.pipe(mergeWith(s2, s3)).subscribe(console.log);


s1.next('1')
s2.next('12')
s3.next('123')

// output 1, 12, 123. 

Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM