Create
You can create an Observable from scratch by using the Create
operator. You pass this operator a function that accepts the observer as its parameter. Write this function so that it behaves as an Observable – by calling the observer’s onNext
, onError
, and onCompleted
methods appropraitely.
A well-formed finite Observable must attempt to call either the observer’s onCompleted
method exactly once or its onError
method exactly once, and must not thereafter attempt to call any of the observer’s other methods.
1 | var source = Rx.Observable.create(function(observer) { |
Defer
Do not create the Observable until the observer subscribes, and create a fresh Observable for each observer.
The Defer
operator waits until an observer subscribes to it, and then it generates an Observable, typically with an Observable factory function. It does this afresh for each subsciber, so although each subscriber may think it is subscribing to the same Observable, in fact each subscriber gets its own individual sequence.
In some circumstances, waiting until the last minute to generate the Observable can ensure that this Observable contains the freshest data.]
1 | var source = Rx.Observable.defer(function () { |
Empty/Never/Throw
Empty
create an Observable that emits no items but terminates normally
Never
create an Observable that emits no items and does not terminates
Throw
create an Observable that emits no items and terminates with an error
The Empty
, Never
, Throw
operators generate Observables with very specific and limited behavior. These are useful for testing purposes, and sometimes also for combining with other Observables or as parameters to operators that expect other Observables as parameters.
1 | var source = Rx.Observable.empty() |
From
Convert various other objects and data types into Observables.
When you work with Observables, it can be more convenient if all of the data you mean to work with can be represented as Observables, rather than as a mixture of Observables and other types. This allows you to use a single set of operators to govern the entire lifespan of the data stream.
Iterables, for example, can be thought of as a sort of synchronous Observable; Futures, as a sort of Observable that always emits only a single item. By explicitly converting such objects to Observables, you allow them to interact as peers with other Observale.
In RxJS, the from
operator converts an array-like or iterable object into an Observable that emits the items in that array or iterable. A String, in this context, is treated as an array of characters.
The operator also takes three additional, optional parameters:
a transforming function that takes an item from the array or iterable as input and produces an item to be emmited by the resulting Observable as output
a second argument to pass into