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.
To create an Observable, you have to first import Observable from RxJS in the.ts file of the component you want to create it in. The creation syntax looks something like this: import { Observable } from "rxjs"; var observable = Observable.create((observer:any) => { observer.next('Hello World!')
An Observable is a lazily evaluated computation that can synchronously or asynchronously return zero to (potentially) infinite values from the time it's invoked onwards. For more info about what to use when converting Observables to Promises, please refer to this guide. Observables as generalizations of functions
Create is a method of the observable object, Hence you do not have to import it. We looked at this in the previous tutorial. There is no difference between the Observable.create method and observable constructor.
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.
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:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With