angularrxjsangular2-servicesrxjs5rxjs-dom

RxJS filter() operator


I am trying to find the cleanest solution to use filter() operator in order to filter my observables.

Here I am replicating the service call to get a femaleList separately

export class MyComp implements OnInit {

    maleList: IContact[] = [];
    femaleList: IContact[] = [];    

    constructor(private _contactService: ContactService) { }
    ngOnInit() : void {
        this._contactService.getContacts()
         .filter(male => male.gender === 'M')
        subscribe(maleList => this.maleList = maleList);

        this._contactService.getContacts()
         .filter(female => female.gender === 'F')
        subscribe(femaleList => this.femaleList = femaleList);
     } }

Contactlist

 [{
      "id" : 1,
      "name" : "Todd",
      "gender" : "M"
    }, {
      "id" : 2,
      "name" : "Lillian",
      "gender" : "F"
    }]

Is there any option in RxJS operators with single observable to assign to two variables.

How can i filter the Contacts and assign it to maleList and femaleList using RxJS filter() operator.

Thanks in advance


Solution

  • You don't need a filter:

    this._contactService.getContacts()
      .subscribe(person => {
        if(person.gender === 'F'){
          this.femaleList.push(person);
        } else {
          this.maleList.push(person);
        }