What does of() do?
of() in RxJS is a function that creates an Observable from the given values.
Example:
ts
of(1, 2, 3).subscribe(value => console.log(value));Outputs:
javascript
1
2
3Each value is like a separate event in the stream.
Why use of():
- To create a simple stream manually
- for tests, demos, or initial values.
- To wrap a value in an
Observable
- especially useful in Angular, where an
Observableis often expected, but you just have a number or a string.
Additional examples:
ts
of('done').subscribe(msg => console.log(msg));
// → donets
const user = { name: 'Maria' };
of(user).subscribe(data => console.log(data));
// → { name: 'Maria' }Conclusion:
of() is a quick way to turn any value (or values) into an Observable.
It simply takes and emits them one by one, then completes the stream.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.