Skip to main content

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 3

Each value is like a separate event in the stream.


Why use of():

  1. To create a simple stream manually
  • for tests, demos, or initial values.
  1. To wrap a value in an Observable
  • especially useful in Angular, where an Observable is often expected, but you just have a number or a string.

Additional examples:

ts
of('done').subscribe(msg => console.log(msg)); // → done
ts
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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.