Create new observable
Here is an example of how to create a new observable in RxJS:
import { Observable, of } from 'rxjs';
// Create a new observable
const myObservable = new Observable(subscriber => {
// Emit values to the subscriber
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
// Complete the observable
subscriber.complete();
});
// Subscribe to the observable
myObservable.subscribe(value => console.log(value));
In this example, we create a new observable using the Observable
constructor. The constructor takes a function as an argument, which is called when the observable is subscribed to. This function is responsible for emitting values to the subscriber.
In this case, we emit the values 1, 2, and 3 to the subscriber, and then complete the observable.
We then subscribe to the observable using the subscribe
method, which takes a callback function as an argument. This callback function is called for each value emitted by the observable.
When we run this code, we should see the values 1, 2, and 3 logged to the console.
Alternatively, you can use the of
function to create an observable that emits a sequence of values:
import { of } from 'rxjs';
const myObservable = of(1, 2, 3);
myObservable.subscribe(value => console.log(value));
This will have the same effect as the previous example, but is often more concise and easier to read.