of
of
is used to emit arguments as values in a sequence and then complete the stream.
Unlike from, it does not do any flattening or conversion and emits each argument as the same type it receives as arguments. If you pass it an Array (including array-like objects), a Promise and an iterable object it won’t be flattened into an observable sequence of values. Those arguments will be emitted as the same type, i.e. an Array, a Promise or an Iterable object without any conversion.
If you need to emit items asynchronously, the operator takes a scheduler as the second argument.
of
operator works in the following way:
- Create an observable instance
- Take the next argument in queue and send it to the observer
- When there are no more values in the data source, send the complete notification to the observer
The following diagram demonstrates this sequence of steps:
UsageLink to this section
of
is commonly used when you simply need to return a value where an observable is expected or start an observable chain. This is a common need when using combination operators like mergeMap
. Here’s an example that checks if there’s a cached value for the URL and if so, returns the value immediately, otherwise it makes a request:
<>Copyfrom(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));
Check this section to learn how mergeMap
operator works.