user3836415
user3836415

Reputation: 982

refactoring combinelatest for rxjs

I'm trying to refactor my code from rxjs 5.x to rxjs 6 and Angular 6. I had a code that essentially triggers a search:

  startAt = new Subject();
  endAt = new Subject();

  startobs = this.startAt.asObservable();
  endobs = this.endAt.asObservable();

  constructor() {}

  ngOnInit(){

    var that = this;

    Observable.combineLatest(this.startobs, this.endobs)
    .subscribe((value) => {
      this.acctServ.searchAccounts(value[0], value[1])
      .subscribe((accounts) => {
console.log("accounts : ", accounts);
          });


      })


    });
  }

In order to refactor this I did the following:

startAt = new Subject();
  endAt = new Subject();

  startobs = this.startAt.asObservable();
  endobs = this.endAt.asObservable();

  constructor() { 

  }//End of Constructor

  ngOnInit() {

    Observable.create().pipe(combineLatest(this.startobs, this.endobs))
    .subscribe((value) => {
      console.log("Search Box Obersable : ", value);

      this.acctServ.searchAccounts(value[0], value[1])
      .subscribe((accounts) => {

        console.log("accounts : ", accounts);
          });


      })


    });

  }//End of ngOnInit

However, this doesn't seem to have helped and the search is no longer being triggered. I was wondering how to actually refactor this code to work with rxjs 6 ?

Upvotes: 1

Views: 488

Answers (1)

martin
martin

Reputation: 96909

You're using combineLatest operator imported from "rxjs/operators" while you should be using combineLatest creation method imported from "rxjs":

What you have now Observable.create().pipe(combineLatest(this.startobs, this.endobs)) is the same as the following:

import { combineLatest } from 'rxjs';

combineLatest(Observable.create(), this.startobs, this.endobs)
  ...

This will never emit anything because combineLatest requires all source Observables to emit at least one value. However Observable.create() doesn't emit anything by itself so combineLatest doesn't emit either.

Instead you should be using just the following:

import { combineLatest } from 'rxjs';

combineLatest(this.startobs, this.endobs)
  ...

Upvotes: 4

Related Questions