RxJS 6 - Recreating isStopped

Problem when using subscriber.error directly

by darrensapalo

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>
<script src="https://cdn.jsdelivr.net/gh/eu81273/jsfiddle-console/console.js"></script>
<h1>
<code>Uncaught TypeError: Cannot read property 'isStopped' of undefined</code>
</h1>

<p>
The problems occur when you incorrectly assume that you can reference <code>subscriber.error</code> <b>as a callback that you can pass as a parameter</b> to some function. </p>
<p>
This is demonstrated below, with the method reference <code>subscriber.error</code>:
</p>

<h3>
Problematic code
</h3>

<p>
The following will throw an error:
</p>

<pre>
  somePromise
  .then(result => {
    subscriber.next(result);
    subscriber.complete();
  })
  .catch(subscriber.error);
</pre>

<h3>
Correct code
</h3>

<p>
To protect the scope of the subscriber object, you instead create an anonymous function:
</p>

<pre>
  somePromise
  .then(result => {
    subscriber.next(result);
    subscriber.complete();
  })
  .catch((error) => subscriber.error(error));
</pre>

<p>
A Typescript example is demonstrated in the JS section of this JS Fiddle.
</p>

CSS

p {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
}

JavaScript

const Rx = rxjs;

Rx.Observable.create(subscriber => {
	
  const someOperation = new Promise((resolve, reject) => {
  	
		reject(Error("Problems man. They're difficult."));
    
  });
  
  someOperation.then(() => {
  	subscriber.next(true);
    subscriber.complete();
  })
   .catch(subscriber.error);
   //.catch((error) => subscriber.error(error));
  
})
  .subscribe(console.log, console.error);