New Observable
New Observable
Up to this point, we have used the fromEvent()
function to create a new Observable.
We can use several creation operators (or functions) to create Observables.
However, we can also use the constructor()
function of the Observable
class to create a new Observable.
Let's look at an example.
import { Observable } from 'rxjs';
/* create a new observable, providing the observer. */
const observable: Observable<string> = new Observable((subscriber) => {
const interval = setInterval(() => {
subscriber.next('Hello from Observableland!');
}, 2000);
// teardown
return () => {
clearInterval(interval);
};
});
/* Subscribe to Notifications. */
observable.subscribe((value) => console.log(value));
See the example on CodeSandbox
Before we explain, let's have a look at the constructor()
function signature:
constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic)
Ok, let's review how to create a new Observable
:
- First, we new up the
Observable
class. - The
constructor()
function requires asubscribe
function that is invoked with asubscriber
and returns theTeardownLogic
interface. - The
subscriber
is an Observer that extendsSubscription
. Don't worry too much about this for now. We'll learn more about Observers and Subscriptions. - What is essential to understand is that the
Subscriber
class has anext()
method. This method emits a next notification to all observers (or consumers/subscribers) of the Observable. - The
Subscriber
returns any teardown logic, which can be function that is invoked when the number of Observers goes from 1 to 0. - In our example, we use the
setInternal()
function to create an interval every 2 seconds. - We invoke the
next()
method on theSubscriber
instance, providing a simple string value. - We then return the teardown function that will clear the interval.
- With our new Observable defined, we invoke the
subscribe()
method, providing thenext
function that is invoked with the next notification value(s).