1

I am quite new to Angular and Javascript, so I was wondering what the following syntax means:

const simpleObservable = new Observable((observer) => {    
    // observable execution
    observer.next("bla bla bla")
    observer.complete()
})

Why is the argument "(observer)" passed in parenthesis to the Observable constructor, and what is the arrow syntax => {...} doing? where can I read about those special constructs in javascript syntax?

MMMM
  • 3,320
  • 8
  • 43
  • 80
  • 2
    Possible duplicate of [What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?](https://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas) – Heretic Monkey Jul 30 '18 at 21:06
  • `observer` does *not* need to be passed within parenthesis. You only need parenthesis if you include the data type e.g. `(observer: any)` or if you have more than one parameter e.g. `(observer, someOtherValue) =>` – DeborahK Jul 30 '18 at 22:11
  • Here is a link to the docs on using an arrow function in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – DeborahK Jul 30 '18 at 22:12

2 Answers2

1

The () => {} syntax denotes a lambda expression. Specifically, a TypeScript lambda expression where the this pointer is set to the actual class (instead of the lambda invoker).

JavaScript lambdas (function() {}) should be avoided as they do not maintain the integrity of this.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

what is the arrow syntax => {...} doing?

Arrow functions are a type of function introduced in the 2015 version of javascript. They are shorter to write and unlike normal functions they take their value of this from the context in which they're declared, not the context in which they're invoked. (though in your particular case, this is not being used, making that distinction irrelevant)

The equivalent using old style functions would be:

const simpleObservable = new Observable(function (observer) {
  // observable execution
  observer.next("bla bla bla")
  observer.complete()
});

Why is the argument "(observer)" passed in parenthesis to the Observable constructor

To construct an observable from scratch, you pass in a function which describes how to do whatever it is you want done. When someone calls .subscribe on the observable your function gets called, and you can do whatever asynchronous stuff you need. And when you have something to report, you can use the .next, .complete, and .error callbacks to output the results.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98