In RxJS (Reactive Extensions for JavaScript), you can emit values 1, 2, 3 using an Observable. Here's how:
✅ Using Observable.create (Basic Example)
import { Observable } from 'rxjs';
const myObservable = new Observable(observer => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete(); // Marks the observable as complete
});
// Subscribe to the observable
myObservable.subscribe({
next: value => console.log(value),
complete: () => console.log('Completed!')
});
// Output:
// 1
// 2
// 3
// Completed!
✅ Using of() (Simpler Way)
import { of } from 'rxjs';
const myObservable = of(1, 2, 3);
myObservable.subscribe(value => console.log(value));
of()creates an observable that emits the given values synchronously.
✅ Using from() (Convert Array to Observable)
import { from } from 'rxjs';
const myObservable = from([1, 2, 3]);
myObservable.subscribe(value => console.log(value));
from()converts an array into an observable that emits items one by one.
✅ Using interval() to Emit 1,2,3 with Delay
import { interval, take } from 'rxjs';
const myObservable = interval(1000).pipe(take(3)); // Emit values every 1s, take 3 values
myObservable.subscribe(value => console.log(value + 1));
// Output: 1, 2, 3 (1 second apart)
interval()emits values at time intervals, andtake(3)ensures it stops after emitting 3 values.
Which One to Use?
-
For synchronous emission →
of(1,2,3) -
For array conversion →
from([1,2,3]) -
For delayed emission →
interval(1000).pipe(take(3)) -
For custom logic (async, API calls, etc.) →
new Observable()
Top comments (0)