RxJS: Observable.create() vs. Observable.from()

Ondra Žižka picture Ondra Žižka · Dec 13, 2016 · Viewed 17.4k times · Source

What's the difference between these two?

return Observable.create(function(observer) {
    if (array)
        observer.next([]);
    else
        observer.next(null);
    observer.complete();
});

and

return Observable.from( array ? [] : null );

I thought it could be the same but didn't work the same.

Answer

paulpdaniels picture paulpdaniels · Dec 13, 2016

The create(...) is a generic Observable factory method for creating an Observable in which you will explicitly dictate how values are passed to the Subscriber

For instance, if you were to create a timer base Observable (don't it already exists as Observable.timer) you could do:

   Observable.create(observer => {
     const timeoutId = setTimeout(() => {
       observer.next(0);
       observer.complete();
     }, 500);

     return () => clearTimeout(timeoutId);
   });

The from(...) is what I call a conformance operator in that it attempts to coerce a passed in data type into an Observable (make it conform). This means that it will accept a variety of types and convert them into Observables. These types include:

  • Arrays
  • Promises
  • Generators
  • Observable-like things

There are specific converters as well that you can find such as fromArray and fromPromise which specifically convert those types, but from more of a swiss-army knife of those methods

If you just need a single value you should be using Observable.of (the docs appear to be out of date, just/return was renamed to of in RxJS 5 and I don't think they are aliased anymore).

i.e.

// Don't quote me on the import part
import 'rxjs/add/observable/of';

Observable.of(1, 2, 3, 4).subscribe();