Q:

How/When does a function returned from Observable.create execute (rxjs)

I have the following code from 'https://chrisnoring.gitbooks.io/rxjs-5-ultimate/content/observable-anatomy.html':
const Observable = require('rxjs/Observable').Observable;
require('rxjs/add/observable/of');
require('rxjs/add/operator/map');

let stream = Observable.create((observer) => {
  let i = 0;
  let id = setInterval(() => {
    observer.next(i++);
  }, 500);

  return function () { // Line 11
    clearInterval(id);
  };
})

let subscription = stream.subscribe((value) => {
  console.log('Value: ', value);
})

setTimeout(() => {
  subscription.unsubscribe();
}, 1500);

The output of this program is below. The program terminates automatically after 'Value: 1' output.
> node index.js

Value:  0
Value:  1

Since the statement is returning a function reference and the returning function does not get called anywhere outside, my question is, how/when does the returning function from line 11 gets executed? We can definitely infer that it is being executed, since the timer is actually getting cleared and node is terminating the program.

A:

The cleanup action function gets run whenever an observer unsubscribes its subscription.
This includes:

calling subscription.unsubscribe()
using some operator like take() that automatically unsubscribes after a condition is met
if/when the observable completes or errors

