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

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();

When you are returning an array, the difference is that 'create/next' will emit the whole array at once but 'from' will emit each item as many times as its length, so to subscriber,

Observable.create(observer => observer.next(myArray)) will fire onNext event once to return myArray whereas Observable.from(myArray) will emit many onNext events to return one item each time.


One difference is: Observable.from() specifically forbids null as something it accepts. So the first is kind of a workaround to create an observable returning null. (See the accepted answer for the main difference though.)

Better (shorter) way would be to use just:

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

But I couldn't find where to get it or how to import it.

import 'rxjs/add/operator/just';

This isn't present in my distribution of rxjs.
Edit: just was renamed to of, see the accepted answer.


Observable.from():
You have a list of values (that has nothing to do with Rx) and an Observable is created from this list. When an Observer subscribe to this Observable, the list of values are passed as Next() events one by one then Completed() is eventually passed and you cannot control this process.

Observable.create():
You create the sequence of event by explicitly emitting the events one by one. Hence, you can emit OnCompleted and OnError events whenever you want