The of Operator

The of function is designed to take its arguments and push them through an observable sequence, finishing with a complete signal once all values have been delivered.

In contrast to from, of does not perform any flattening or type conversion. Each argument is emitted exactly as supplied. For example, if you hand it an array, a promise, or an iterable, none of these get broken down into individual emissions. They are simply passed along as single values—respectively an array, a promise, or an iterable—without further processing.

To emit items asynchronously, you can pass a scheduler as the second parameter to the operator.

Here is the operational flow of of:

  1. An observable instance gets created.
  2. The operator takes the next argument waiting in line and pushes it to the observer.
  3. Once the source has no more values, it issues a complete notification to the observer.

When to Use of

The of operator comes in handy when you want to return a value in a context where an observable is expected or when kicking off an observable chain. This scenario frequently occurs with combination operators such as mergeMap.

Take a look at this example, which checks for a cached value corresponding to a URL. If a cached entry is found, it returns that value right away; otherwise, it proceeds with an actual request:

from(urls).pipe(
   mergeMap((url) => {
       const cached = cache[url];
       // here we use `of` to create an observable from a plain value
       if (cached) return of(cached);
       return fromFetch(url).pipe(switchMap(response => response.json()));
   })
).subscribe((value) => console.log(value));

For more details on how mergeMap works, refer to this explanation.

Playground

Further Reading