Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird javascript syntax return {unsubscribe() {}};

I found weird construction in angular tutorial. What is going on in return section? Function call inside code block followed by empty object?

// This function runs when subscribe() is called
function sequenceSubscriber(observer) {
  // synchronously deliver 1, 2, and 3, then complete
  observer.next(1);
  observer.next(2);
  observer.next(3);
  observer.complete();

  // unsubscribe function doesn't need to do anything in this
  // because values are delivered synchronously
  return {unsubscribe() {}};
}

// Create a new Observable that will deliver the above sequence
const sequence = new Observable(sequenceSubscriber);

// execute the Observable and print the result of each notification
sequence.subscribe({
  next(num) { console.log(num); },
  complete() { console.log('Finished sequence'); }
});

// Logs:
// 1
// 2
// 3
// Finished sequence
like image 291
k-mx Avatar asked May 08 '26 12:05

k-mx


1 Answers

You say that the code return {unsubscribe() {}}; is a "Function call inside code block followed by empty object"; that is incorrect.

What is actually happening is that the function, sequenceSubscriber, is returning an Object with a function named "unsubscribe" as a property. That function does nothing. This is utilizing the new function shorthand you can see here: Method definitions

Consider the code:

const foo = {
    bar(){}
};

creates an Object foo that has a function, bar, that does nothing.

The reason why it is doing this is to fulfill the interface contract that Rx defines for Observables as well as the Subscription interface defined in the tc39/proposal-observable:

interface Subscription {

    // Cancels the subscription
    unsubscribe() : void;

    // A boolean value indicating whether the subscription is closed
    get closed() : Boolean;
}
like image 183
zero298 Avatar answered May 10 '26 02:05

zero298



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!