Joel Lau
Joel Lau

Reputation: 89

Difference between .subscribe(x=> ...) and .subscribe(next(...))?

I'm trying to test the output of a Subject symbol$ that exists on my component. Specifically, Subject symbol$ should emit (is this the right word here?) a value whenever the component property symbol has changed.

However, I could not find a way to test the output to symbol$ until I came across a chunk of code online that uses the .subscribe(next() { ... }) instead of .subscribe((x) => {...}); syntax.

What is the difference between the 2 calls? And why does only 1 of these work?

it('should fetch data', () => {
  const actuals: string[] = [];

  // commented version doesn't work
  // component.symbol$.subscribe((symbol) => { actuals.push(symbol); } ;

  component.symbol$.subscribe({
    next(symbol) {
      actuals.push(symbol);
    },
  });

  expect(actuals).toEqual(['']);
  component.symbol = 'IBM';
  component.ngOnChanges();

  expect(actuals).toEqual(['', 'IBM']);
});

Upvotes: 7

Views: 2460

Answers (1)

DeborahK
DeborahK

Reputation: 60518

There is a difference in passing arrow functions vs normal functions into the subscribe, specifically around this.

Observer with Arrow Functions: enter image description here

Observer with Function Declarations: enter image description here

But watch out for this:

const sub = source$.subscribe({
  next(apple) { this.apple = apple }, // Does NOT reference the 
                                      // class-level variable
  error(err) { console.log(`Error occurred: ${err}`)},
  complete() { console.log(`No more apples, go home`)}
});

Since this is scoped to a function, the this within the next(apple) function will not reference any class-level variable but will assume you are defining a new variable local to the next(apple) function.

That is not the case with arrow functions. this within an arrow function is scoped to the class-level variable.

Upvotes: 7

Related Questions